Calling Activity from Async Task

2019-04-17 22:42发布

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条回答
我只想做你的唯一
2楼-- · 2019-04-17 22:50

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));
  }
}
查看更多
登录 后发表回答