Calling Activity from Async Task

2019-04-17 22:50发布

问题:

I am unable to call an activity from async task, i have tried different ways but every time i get a null pointer exception in the log cat.

I have tried this.

@Override
protected void onPostExecute(String result) {



    if(signedin==false)
    {
        Toast.makeText(XMPPClient.context, "authentication failed:", Toast.LENGTH_LONG).show();                
    }
    Intent i = new Intent(getApplicationContext(), ProfileHome.class);
    startActivity(i);

}

and this

@Override
protected void onPostExecute(String result) {


    XMPPClient xmpp = new XMPPClient();
    if(signedin==false)
    {
        Toast.makeText(XMPPClient.context, "authentication failed:", Toast.LENGTH_LONG).show();                
    }else
        xmpp.startnewactivity();

}

And in XMPPClient.class

public void startnewactivity()
{
    Intent i = new Intent(getApplicationContext(), ProfileHome.class);
    startActivity(i);
}

How can i call an activity from async task, actually I want to call activity when async task finishes.

回答1:

I believe the problem is here:

Intent i = new Intent(getApplicationContext(), ProfileHome.class);

Usually, using getApplicationContext() as a Context is a very bad idea unless you really know what are you doing. Instead, you should use the Context of the Activity that you want to start the new from. You can achieve this passing it as a value on .execute() or even storing the Context you get in the AsyncTask's constructor and store it, so you later can use it in your onPostExecute() method.

---- EDIT ----

This would be an example:

public class MyAsyncTask extends AsyncTask {
   Context context;

   private MyAsyncTask(Context context) { this.context = context; }

   @Override
   protected void onPostExecute(...) {
     super.onPostExecute(result);

     context.startActivity(new Intent(context, ProfileHome.class));
  }
}