AsyncTask 在片段的 onCreateView 上没有结果
AsynTask no results on onCreateView of fragment
我不明白我的错误在哪里。我有一个 Fragment
,在 onCreateView
上我创建并执行了一个 AsyncTask
。但没有显示任何结果。
我的片段
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.thread_layout, container, false);
TextView tv = (TextView) view.findViewById(R.id.textView1);
ThreadAsyncTask threads = new ThreadAsyncTask(addressOfThread);
threads.execute();
tv.setText(threads.getResulf());
return view;
}
}
和我的 AsyncTask
public class ThreadAsyncTask extends AsyncTask<String, Void, String> {
private String addressOfThread = "";
public String resulf = "aaaa";
public ThreadAsyncTask(String url) {
this.addressOfThread = url;
}
public String getResulf(){
return new String(this.result);
}
}
您需要实现 doInBackground 方法,在此方法中您需要指定您希望任务在单独的线程中执行的操作。
在此之后,如果您需要使用从 doInBaackground 获得的结果修改 UI,则必须实现 onPostExecute 方法。
您必须覆盖 doInBackground
方法以 get/handling 您的数据。
此数据 在 onPostExecute
方法中可用,并从此处将其回调到您的 UI(Activity 或片段)。
请查看我的示例 gits 以了解此过程:
异步任务:https://gist.github.com/hongthaiis/77a847d2011f627c2c60#file-getweatherdatatask-java
Activity 回调方法:https://gist.github.com/hongthaiis/43477678bb2764cfc0f6#file-weatheractivity-java
希望对您有所帮助! :D
我不明白我的错误在哪里。我有一个 Fragment
,在 onCreateView
上我创建并执行了一个 AsyncTask
。但没有显示任何结果。
我的片段
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.thread_layout, container, false);
TextView tv = (TextView) view.findViewById(R.id.textView1);
ThreadAsyncTask threads = new ThreadAsyncTask(addressOfThread);
threads.execute();
tv.setText(threads.getResulf());
return view;
}
}
和我的 AsyncTask
public class ThreadAsyncTask extends AsyncTask<String, Void, String> {
private String addressOfThread = "";
public String resulf = "aaaa";
public ThreadAsyncTask(String url) {
this.addressOfThread = url;
}
public String getResulf(){
return new String(this.result);
}
}
您需要实现 doInBackground 方法,在此方法中您需要指定您希望任务在单独的线程中执行的操作。 在此之后,如果您需要使用从 doInBaackground 获得的结果修改 UI,则必须实现 onPostExecute 方法。
您必须覆盖 doInBackground
方法以 get/handling 您的数据。
此数据 在 onPostExecute
方法中可用,并从此处将其回调到您的 UI(Activity 或片段)。
请查看我的示例 gits 以了解此过程:
异步任务:https://gist.github.com/hongthaiis/77a847d2011f627c2c60#file-getweatherdatatask-java
Activity 回调方法:https://gist.github.com/hongthaiis/43477678bb2764cfc0f6#file-weatheractivity-java
希望对您有所帮助! :D