mokko211
mokko211

Reputation: 607

How to pass the context from an activity to an AsyncTask class to start a new Activity?

I am trying to pass the Context from an activity to a AsyncTask class. The problem is that the context is null.

In my AsyncTask class, I have the following

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

      ....

 public Context context;


 public LoginService(){

}

public LoginService(String username, String password){
    this.username=username;
    this.password=password;
}


@Override
protected String doInBackground(String... params) {

    String userID = login(username, password);

    return userID;
}

protected void onPostExecute(String result){

     loginSuccess = result;

    if (loginSuccess!=fail){
       Intent casesActivity = new Intent(context, CasesActivity.class);
       casesActivity.putExtra("username", result);
       context.startActivity(casesActivity);
}

public void setContext(Context newContext){
    context = newContext;
}

And in my activity, when I click a button, I have the following code:

 public void onClick(View view) {

            if ((editTextPassword.getText().toString() != null & editTextUsername.getText().toString() != null)){

                new LoginService().setContext(getApplicationContext());
                new LoginService(editTextUsername.getText().toString(), editTextPassword.getText().toString()).execute();

             }
            else{
                //Display Toaster for error
                Toast.makeText(getApplicationContext(),"Please enter your details", Toast.LENGTH_LONG).show();
            }
        }

The intent is never created and the application crashes abruptly because the context is null. I cannot seem to find the solution for this issue.

Upvotes: 2

Views: 1565

Answers (1)

A--C
A--C

Reputation: 36449

For a minimal code change, keep a reference to your LoginTask instead of creating two separate instances:

LoginService l = new LoginService(editTextUsername.getText().toString(), editTextPassword.getText().toString());

l.setContext (getApplicationContext());

l.execute();

Your code creates a new LoginTask every time, and since you have two separate constructors, context is always null (the second constructor doesn't hold the context, since you created a separate Object!)

However, if you want a Context passed off along with the user creds, take out the no argument constructor and change the remaining one so it looks like:

public LoginService(Context context,String username, String password){
    this.context = context;
    this.username=username;
    this.password=password;
}

Having empty constructors that do nothing is usually pointless, so adjust your useful constructor so it is even more useful.

Upvotes: 3

Related Questions