【发布时间】:2014-07-06 08:59:35
【问题描述】:
我正在使用 http get 连接到一个站点并从中检索一些数据。为此,我需要定义asyncTask 方法并使用asyncTask get 方法来检索doInBackground 方法中生成的结果。
我从服务器获取数据的辅助方法非常好,因此无需在此处发布它们。当我调用new LongOperation().execute().get() 时,应用程序崩溃。当我调试代码时,它会打开新窗口并显示Source not Found。
这是我的代码:
Main activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_notification);
try {
ArrayList<Job> JobsStore = new LongOperation().execute().get();
} catch (Exception e) {
// TODO: handle exception
}
...
asyncTask Methods:
public class LongOperation extends AsyncTask<Void, Void, ArrayList<Job>> {
private final static String USER_AGENT = "Mozilla/5.0";
protected ArrayList<Job> doInBackground(String... params) {
ArrayList<Job> JobsStore = SendRSSFeed();
return JobsStore;
}
@Override
protected void onPostExecute(ArrayList<Job> result) {
super.onPostExecute(result);
}
...
我在这里做错了什么?
谢谢。
【问题讨论】:
-
请发布 logcat。可能
ArrayList<Job> JobsStore = SendRSSFeed();行抛出空指针异常。 -
不要使用
get(),因为 UI 会冻结,而不是使用onPostExecute并使用其中的数据 -
不应该是
ArrayList<Job> JobsStore = new LongOperation().get();吗? -
使用 get() 违背了异步任务的目的。强烈建议不要使用它。
标签: android android-activity android-asynctask