如何从 Android 中的 PostExecute 正确启动活动? [英] How to correctly start activity from PostExecute in Android?
问题描述
我有一个 AsyncTask,它用来自 Internet 的解析数据填充自定义列表.
I have an AsyncTask, that fills a custom List with parsed data from Internet.
在 PostExecute 中,我填写该列表并准备好将其传输到新活动.
In PostExecute I fill that List and get it ready to transfer it to a new Activity.
我是这样做的:
@Override
protected void onPostExecute(List<VideoDataDescription> result)
{
super.onPostExecute(result);
MainActivity.progressDialog.dismiss();
context.startActivity(new Intent(context, ResultsQueryActivity.class));
}
上下文
private Context context;
在执行此代码后的 LogCat 中,我得到一个 Java.lang.NullPointerException.像我一样启动 Activity 是否可能且正确?
In LogCat after executing this code I get a Java.lang.NullPointerException. Is this possible and correct to start an Activity as I do it?
UPD我已经添加
private Context mContext;
public YoutubeAndYahooParser(Context context)
{
super();
this.mContext = context;
}
初始化上下文并调用
YoutubeAndYahooParser youtubeAndYahooParser = new YoutubeAndYahooParser(ResultsQueryActivity.this);
youtubeAndYahooParser.execute("my string to pass in asynctak");
在 PostExecute 之后
After this in PostExecute
Intent intent = new Intent(mContext, ResultsQueryActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
我添加了新标志,因为我接下来进入了 LogCat:
I added new flag because of I have got in LogCat the next:
*从活动上下文外部调用 startActivity() 需要 FLAG_ACTIVITY_NEW_TASK 标志.这真的是你想要的吗?*
*Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?*
我说得对吗?
推荐答案
您应该传入应用程序上下文而不是来自本地活动的上下文.IE.使用 context.getApplicationContext() 并将其保存在 AsyncTask 子类中的局部变量中.
You should pass in the application context rather than a context from the local activity. I.e. use context.getApplicationContext() and save that in a local variable in your AsyncTask subsclass.
代码可能如下所示:
public class MyAsyncTask extends AsyncTask {
Context context;
private MyAsyncTask(Context context) {
this.context = context.getApplicationContext();
}
@Override
protected Object doInBackground(Object... params) {
...
}
@Override
protected void onPostExecute(List<VideoDataDescription> result) {
super.onPostExecute(result);
MainActivity.progressDialog.dismiss();
context.startActivity(new Intent(context, ResultsQueryActivity.class));
}
}
你会这样称呼它:
new MyAsyncTask(context).execute();
这篇关于如何从 Android 中的 PostExecute 正确启动活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!