如何正确地从PostExecute开始在Android的活动? [英] How to correctly start activity from PostExecute in Android?
问题描述
我有一个AsyncTask的,填充来自互联网的解析数据的自定义列表。
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));
}
在这里的上下文
where context
private Context context;
在LogCat中执行此code,我收到了显示java.lang.NullPointerException之后。 这是可能的,正确的启动活动,因为我做到这一点?
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;
}
要初始化上下文,并调用
to initialize context and call
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?*
我说得对不对?
推荐答案
您应该通过在应用程序上下文,而不是从本地活动上下文。即使用context.getApplicationContext()并保存在你的AsyncTask subsclass的局部变量。
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.
在code力量看起来是这样的:
The code might looks something like this:
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));
}
}
你会这样称呼它:
you'd call it like this:
new MyAsyncTask(context).execute();
这篇关于如何正确地从PostExecute开始在Android的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!