Starting intent after Async task gets over

2019-02-28 03:27发布

I created a login activity for my Android app. After the user enters the correct credentials, the login activity will switch over to the homepage but I don't know why my code won't switch and there is no error shown in my logcat. The manifest was also properly defined.

This is my login activity:

public class LoginEmployerActivity extends Activity { 
Button btnLoginEmployer; 
Button btnLinkToEmployerRegisterScreen; 
EditText inputEmail; 
EditText inputPassword; 
TextView loginErrorMsg; 
TextView forgotPassword; 

// JSON Response node names 
private static String KEY_SUCCESS = "success"; 
private static String KEY_ERROR = "error"; 
private static String KEY_ERROR_MSG = "error_msg"; 
private static String KEY_UID = "uid"; 
private static String KEY_NAME = "name"; 
private static String KEY_CNAME = "cname"; 
private static String KEY_EMAIL = "email"; 
private static String KEY_CREATED_AT = "created_at"; 
private ProgressDialog pDialog; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.login_employer); 

// Importing all assets like buttons, text fields 
inputEmail = (EditText) findViewById(R.id.loginEmployerEmail); 
inputPassword = (EditText) findViewById(R.id.loginEmployerPassword); 
btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer); 
btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen); 
loginErrorMsg = (TextView) findViewById(R.id.login_error); 
forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword); 

// Login button Click Event 
btnLoginEmployer.setOnClickListener(new View.OnClickListener() { 

    public void onClick(View view) { 
        // Checking for server respond 
            new LoginEmployer().execute(); 
        } 
    } 
}); 

// Link to Register Screen 
btnLinkToEmployerRegisterScreen 
        .setOnClickListener(new View.OnClickListener() { 

            public void onClick(View view) { 
                Intent i = new Intent(getApplicationContext(), 
                        RegisterEmployerActivity.class); 
                startActivity(i); 
                finish(); 
            } 
        }); 

// Link to forgot password link 
forgotPassword.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View view) { 
        // Switching to forgot password screen 
        Intent i = new Intent(getApplicationContext(), 
                ForgotPasswordEmployerActivity.class); 
        startActivity(i); 
    } 
}); 
} 

// Background ASYNC Task to login by making HTTP Request 
class LoginEmployer extends AsyncTask<String, String, String> { 

// Before starting background thread Show Progress Dialog 
@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    pDialog = new ProgressDialog(LoginEmployerActivity.this); 
    pDialog.setMessage("Authenticating..."); 
    pDialog.setIndeterminate(false); 
    pDialog.setCancelable(false); 
    pDialog.show(); 
} 

// Checking login in background 
protected String doInBackground(String... params) { 
    runOnUiThread(new Runnable() { 
        public void run() { 

            String email = inputEmail.getText().toString(); 
            String password = inputPassword.getText().toString(); 
            EmployerFunctions employerFunctions = new EmployerFunctions(); 
            JSONObject json = employerFunctions.loginUser(email, 
                    password); 

            // check for login response 
            try { 
                if (json.getString(KEY_SUCCESS) != null) { 
                    loginErrorMsg.setText(""); 
                    String res = json.getString(KEY_SUCCESS); 
                    if (Integer.parseInt(res) == 1) { 
                        // user successfully logged in 
                        // Store user details in SQLite Database 
                        DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer( 
                                getApplicationContext()); 
                        JSONObject json_user = json 
                                .getJSONObject("user"); 

                        // Clear all previous data in database 
                        employerFunctions 
                                .logoutUser(getApplicationContext()); 
                        dbe.addUser( 
                                json_user.getString(KEY_NAME), 
                                //json_user.getString(KEY_CNAME), 
                                json_user.getString(KEY_EMAIL), 
                                json.getString(KEY_UID), 
                                json_user.getString(KEY_CREATED_AT)); 
                        // Launch Employer homePage Screen 
                        Intent homepage = new Intent( 
                                getApplicationContext(), 
                                HomepageEmployerActivity.class); 

                        // Close all views before launching Employer 
                        // homePage 
                        homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                        startActivity(homepage); 

                        // Close Login Screen 
                        finish(); 
                    } else { 
                        // Error in login 
                        loginErrorMsg 
                                .setText("Invalid username/password"); 
                    } 
                } 
            } catch (JSONException e) { 
                e.printStackTrace(); 
            } 
        } 
    }); 
    return null; 
} 

// After completing background task Dismiss the progress dialog 
protected void onPostExecute(String file_url) { 
    // dismiss the dialog once done 
    pDialog.dismiss(); 
} 
} 
}

EDITED CODE AFTER MOVING INTENT STATEMENT TO onPostExecute METHOD

public class LoginEmployerActivity extends Activity {
Button btnLoginEmployer;
Button btnLinkToEmployerRegisterScreen;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView forgotPassword;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_CNAME = "cname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private ProgressDialog pDialog;

boolean loginVerify= false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_employer);

    // Importing all assets like buttons, text fields
    inputEmail = (EditText) findViewById(R.id.loginEmployerEmail);
    inputPassword = (EditText) findViewById(R.id.loginEmployerPassword);
    btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer);
    btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen);
    loginErrorMsg = (TextView) findViewById(R.id.login_error);
    forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword);

    // Login button Click Event
    btnLoginEmployer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // Checking for server respond
                new LoginEmployer().execute();
            }
        }
    });

    // Link to Register Screen
    btnLinkToEmployerRegisterScreen
            .setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),
                            RegisterEmployerActivity.class);
                    startActivity(i);
                    finish();
                }
            });

    // Link to forgot password link
    forgotPassword.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Switching to forgot password screen
            Intent i = new Intent(getApplicationContext(),
                    ForgotPasswordEmployerActivity.class);
            startActivity(i);
        }
    });
}

// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {

    // Before starting background thread Show Progress Dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginEmployerActivity.this);
        pDialog.setMessage("Authenticating...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    // Checking login in background
    protected String doInBackground(String... params) {
        runOnUiThread(new Runnable() {
            public void run() {

                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                EmployerFunctions employerFunctions = new EmployerFunctions();
                JSONObject json = employerFunctions.loginUser(email,
                        password);

                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        loginErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
                        if (Integer.parseInt(res) == 1) {
                            loginVerify = true;
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer(
                                    getApplicationContext());
                            JSONObject json_user = json
                                    .getJSONObject("user");

                            // Clear all previous data in database
                            employerFunctions
                                    .logoutUser(getApplicationContext());
                            dbe.addUser(
                                    json_user.getString(KEY_NAME),
                                    json_user.getString(KEY_CNAME),
                                    json_user.getString(KEY_EMAIL),
                                    json.getString(KEY_UID),
                                    json_user.getString(KEY_CREATED_AT));

                        } else {
                            // Error in login
                            loginErrorMsg
                                    .setText("Invalid username/password");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        return null;
    }

    // After completing background task Dismiss the progress dialog
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
        if ( loginVerify == true ) 
        {
        // Launch Employer homePage Screen
        Intent homepage = new Intent(getApplicationContext(),
                HomepageEmployerActivity.class);

        // Close all views before launching Employer
        // homePage
        homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(homepage);

        // Close Login Screen
        finish();
        }
    }
}

}

3条回答
Luminary・发光体
2楼-- · 2019-02-28 03:50

I don't think you have added the Intent code here that will help you switch to another Activity.

protected void onPostExecute(String file_url) { 

    // dismiss the dialog once done             // Intent Code Missing.

    pDialog.dismiss(); 

You should do a UI work in UI thread and Non-UI work in Non-UI thread, thats a rule from the arrival of HoneyComb version of android.

You have added the below code in doInBackground(), That should be in onPostExcute()

Intent homepage = new Intent( getApplicationContext(), HomepageEmployerActivity.class); 
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(homepage);
查看更多
迷人小祖宗
3楼-- · 2019-02-28 03:56

Add a checker to your AsyncTask such as

// Background ASYNC Task to login by making HTTP Request 
class LoginEmployer extends AsyncTask<String, String, String> { 

boolean validUser = false;

Then once the user is validated inside your background task set the value to true

 if (Integer.parseInt(res) == 1) { 
      // user successfully logged in 
      // Store user details in SQLite Database 

     validUser = true;  //set valid to true

Now in postExecute check if the user is valid

protected void onPostExecute(String file_url) { 
    // dismiss the dialog once done 
    pDialog.dismiss(); 
    if ( validUser )
    {
        Intent homepage = new Intent( LoginEmployerActivity.this, 
        HomepageEmployerActivity.class); 

        // Close all views before launching Employer 
        // homePage 
         homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         startActivity(homepage); 
    }
查看更多
狗以群分
4楼-- · 2019-02-28 04:00

You are calling the intent to start a new activity inside the doInBackgorund() which runs on a non-UI thread and the Activity needs to be run on a UI thread. That is why your Login activity is never stopped.

Put the code to go to the new activity inside onPostExecute() or onProgressUpdate().

Here is something you can do. Declare a global variable loginVerfied = false;

When your doInBackground verifies that the authenticity of the user, make loginVerified = true , otherwise keep it false.

Then inside onPostExecute()

if(loginVerifed == true)
{
       Intent homepage = new Intent(getApplicationContext(),HomepageEmployerActivity.class                               
       homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(homepage);
       finish();
}

EDIT :

Also, you have declared class LoginEmployer extends AsyncTask<String, String, String>, so to call it you need to use new LoginEmployer.execute(""); (you are missing the double quotes and not passing any String to the Task so it does not match it's parameters). The first parameter in the definition of the AsyncTask is the datatype of the value being passed to it when execute() function is called. The second parameter is the datatype related to displaying progress during the time when the background thread runs. And the third parameter specifies the return value of the result.

More about AsyncTask here.

So, here is what you need to do now.

Declare the Async Task like this.

class LoginEmployer extends AsyncTask<String, Void, String> and make a call to it by using new LoginEmployer.execute(""). Make sure to return null from your doInBackground().

Hope this solves your problem now!

查看更多
登录 后发表回答