简体   繁体   中英

How can I load the new activity after login in android studio?

Basically, I want to start a new activity after login using the database. How can I do that?

This is my login class

public class login extends AppCompatActivity {

    EditText username;
    EditText password;
    Button btn_login;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        btn_login = (Button) findViewById(R.id.btn_login);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String user = username.getText().toString();
                String pass = password.getText().toString();
                String type = "login";
                System.out.println("IN Onclick login");
                BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
                backgroundTask.execute(type,user,pass);

                  if(backgroundTask.statusOK.equals("true"))     {
                      Intent loginIntent = new Intent(login.this,loggedIn.class);
                      startActivity(loginIntent);
                  }

            }




        });


    }


}

You can see in the code above that I am using this code to start my new activity after successful login, but this is not starting a new activity. I don't know why?

if(backgroundTask.statusOK.equals("true"))     {
                      Intent loginIntent = new Intent(login.this,loggedIn.class);
                      startActivity(loginIntent);
                  }

This is BackgroundTask class

public class BackgroundTask extends AsyncTask<String, String, String> {


    Context context;
    public String statusOK="false";




    BackgroundTask(Context ctx){
        this.context = ctx;

    }


    @Override
    protected String doInBackground(String... strings) {
          System.out.println("In doin");
        String type = strings[0];
        String loginURL = "http://192.168.10.119/log/login.php";
        String regURL = "http://192.168.10.119/log/log.php";

        if(type.equals("reg")){
            String name = strings[1];
            String pass = strings[2];
            try{
                URL url = new URL(regURL);
                try {
                    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
                    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

                    String insert_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+
                            "&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass,"UTF-8");

                    bufferedWriter.write(insert_data);
                    bufferedWriter.flush();
                    bufferedWriter.close();

                    InputStream inputStream = httpURLConnection.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String result="";
                    String line="";
                    StringBuilder stringBuilder = new StringBuilder();

                    while((bufferedReader.readLine())!= null){
                        stringBuilder.append(line).append("\n");
                    }
                    result = stringBuilder.toString();
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    return result;




                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        else if(type.equals("login")){
            System.out.println("In type = login");
            String name1 = strings[1];
            String pass1 = strings[2];
            try{
                URL url = new URL(loginURL);
                try {
                    System.out.println("In type = login try");
                    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
                    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

                    String login_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name1,"UTF-8")+
                            "&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass1,"UTF-8");

                    bufferedWriter.write(login_data);
                    bufferedWriter.flush();
                    bufferedWriter.close();

                    InputStream inputStream = httpURLConnection.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String result="";
                    String line="";
                    StringBuilder stringBuilder = new StringBuilder();

                    while((bufferedReader.readLine())!= null){
                        stringBuilder.append(line).append("\n");
                    }
                    result = stringBuilder.toString();
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();

                    return result;



                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }



        return null;

    }


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

    @Override
    protected void onPostExecute(String s) {
        statusOk="true";

        Toast.makeText(context, "Successful", Toast.LENGTH_LONG).show();


        //super.onPostExecute(s);
    }



}

I have checked the connection between the database and my app is established and the app is running without any error.

You can see in the code above that I have created a public variable statusOk and initialize it with "false" . This variable is telling the login class that the user have entered his correct login credentials.

You can see that I have changed the value of statusOk to "true" onPostExexute method.

Now the problem is my new activity is not opening from the login class after successful login. Please give me a solution how can I open a new activity after Login with correct login credentials.

Asynctask is used to execute task in the background thread, (not the main thread from where you have called the execute() ).

Therefore in your code, if statement is executed just after you called the execute() , which still store the variable statusOK as false. Hence the condition is false.

The postExecute() method of asynctask is used to execute code in the main thread,

My suggestion : remove the if condition from the Login class, and check for the if condition in the postExecute() ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM