Как сделать в alertDialog, нажав OK, затем перейти на следующую страницу? - PullRequest
0 голосов
/ 21 сентября 2019

Мои проблемы:

1.У меня есть ошибка.

2.Почему я не могу перейти на следующую страницу, когда я использую startActivity?

3.Как решить?

4.Я уже использую startActivity, используя метод Intent

Ниже приведено доказательство 1:

enter image description here

Ниже доказано 2:

enter image description here

Ниже доказано 3:

enter image description here

Ниже приведен фрагмент кода:

 public void OnLog(View view)
 {
    String Username = username.getText().toString();
    String Password = password.getText().toString();
    String type = "login";

    if(Username.equals("") || Password.equals(""))
    {
        Toast.makeText(getApplicationContext(), "Please fill the Username and Password!", Toast.LENGTH_LONG).show();
    }
    else {

        Background bg = new Background(Context, act);
        bg.execute(type, Username, Password);
    }
}

enter image description here

Ниже кодируется Background.java :

public class Background extends AsyncTask<String,Void,String> {

Context context;
AlertDialog alertDialog;

Background(Context ctx) {
    context = ctx;
}

@Override
protected String doInBackground(String... params)
{
    String type = params[0];
    String login_url = "http://172.20.10.4/LoginLab3.php";
    String reg_url = "http://172.20.10.4/RegisterLab3.php";
    if (type.equals("login")) {
        try {
            String username = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
                    + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
            String result = "";
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    else if(type.equals("register"))
    {
        try {
            String name = params[1];
            String surname = params[2];
            String age = params[3];
            String username = params[4];
            String password = params[5];
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
                    +URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
                    +URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
                    +URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null)
            {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute()
{
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result)
{
    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setTitle("Login Status");
    dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            startActivity(new Intent(Login.this, Welcome.class));
        }
    });
    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
    dialog.create().show();
}

@Override
protected void onProgressUpdate(Void... values)
{
    super.onProgressUpdate(values);
}
}

Помогите мне!У меня есть некоторые проблемы.Я уже использую почти все методы, но не могу перейти на следующую страницу.Почему?

Ответы [ 2 ]

1 голос
/ 21 сентября 2019

Код действия при создании

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Pass activity to Async Task
    new Background(this).execute();
 }  

Асинхронная задача

public class Background extends AsyncTask<Void,Void,Void> {
    private Context context;

    public Background(Context context){
        this.context=context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Intent intent = new Intent(context, TargetActivity.class);
        context.startActivity(intent);
        ((Activity)context).finish();
    }
}
1 голос
/ 21 сентября 2019

Попробуйте context.startActivity(), поскольку AsyncTask класс не имеет наследуемого метода startActivity().

Кроме того, передайте действие в конструкторе, назначьте его переменной и используйте эту переменную при создании намерения

Context context;
Activity activity;
AlertDialog alertDialog;

Background(Context ctx, Activity act) {
    context = ctx;
    activity = act;
}

внутри onClick()

context.startActivity(new Intent(activity, Welcome.class));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...