从异步调用任务活动 [英] Calling Activity from Async Task
问题描述
我无法调用从异步任务的活动,我已经尝试过不同的方法,但每次我在日志猫空指针异常。
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.
我已经试过这一点。
@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);
}
这
@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();
}
而在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.
推荐答案
我相信问题就在这里:
Intent i = new Intent(getApplicationContext(), ProfileHome.class);
一般情况下,使用 getApplicationContext()
为上下文
是一个非常糟糕的主意,除非你真的知道什么是你这样做。相反,你应该使用上下文
的活动
,你要开始新的。你可以做到这一点把它当作对 .execute()
,甚至存储上下文
您在获得<值code>的AsyncTask 的构造和储存,所以你以后可以在 onPostExecute()
方法使用它。
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.
---- ----编辑
这将是一个例子:
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));
}
}
这篇关于从异步调用任务活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!