我有一个自定义ListAdapter的获取数据从互联网中的AsyncTask。
中的数据完全添加到列表中,但是当我尝试做业务应用程序崩溃...
我敢肯定,这是因为我打电话notifyDataSetChanged();在错误的时间(即AsyncTask的结束之前)。
我有什么现在的:
公共类MyListAdapter扩展了BaseAdapter {
私人的ArrayList<字符串> mStrings =新的ArrayList<字符串>();
公共MyListAdapter(){
新RetreiveStringsTask()执行(internet_url);
//这里我所说的通知功能****************
this.notifyDataSetChanged();
}
类RetreiveStringsTask扩展的AsyncTask<字符串,无效的ArrayList<字符串>> {
私人例外的例外;
@覆盖
受保护的ArrayList<字符串> doInBackground(字符串...网址){
尝试 {
网址URL =新的URL(网址[0]);
//返回数组列表
返回getStringsFromInternet(URL);;
}赶上(例外五){
this.exception = E;
Log.e(AsyncTask的,exception.toString());
返回null;
}
}
@覆盖
保护无效onPostExecute(ArrayList中<字符串> stringsArray){
//从互联网上添加旅行团到数组
如果(stringsArray!= NULL){
mStrings.addAll(toursArray);
}
}
}
}
我的问题是:我可以打电话notifyDataSetChanged()从AsyncTask的,或在其他任何时间的onPostExecute功能,当AsyncTask的已取出的数据
? 解决方案我可以调用notifyDataSetChanged()从onPostExecute功能 在AsyncTask的
是的,你可以叫 notifyDataSetChanged()
从 onPostExecute
来更新适配器数据时 doInBackground
执行完毕。做到这一点的:
@覆盖
保护无效onPostExecute(ArrayList中<字符串> stringsArray){
//从互联网上添加旅行团到数组
如果(stringsArray!= NULL){
mStrings.addAll(toursArray);
//调用notifyDataSetChanged()在这里...
MyListAdapter.this.notifyDataSetChanged();
}
}
I've a custom ListAdapter that fetches data from internet in an AsyncTask.
The data is added perfectly to the list, but when I try to do operations the application crashes...
I'm sure this is because I'm calling notifyDataSetChanged(); at the wrong time (i.e. before the AsyncTask ends).
What I've got now:
public class MyListAdapter extends BaseAdapter {
private ArrayList<String> mStrings = new ArrayList<String>();
public MyListAdapter() {
new RetreiveStringsTask().execute(internet_url);
//here I call the notify function ****************
this.notifyDataSetChanged();
}
class RetreiveStringsTask extends AsyncTask<String, Void, ArrayList<String>> {
private Exception exception;
@Override
protected ArrayList<String> doInBackground(String... urls) {
try {
URL url= new URL(urls[0]);
//return arraylist
return getStringsFromInternet(url);;
} catch (Exception e) {
this.exception = e;
Log.e("AsyncTask", exception.toString());
return null;
}
}
@Override
protected void onPostExecute(ArrayList<String> stringsArray) {
//add the tours from internet to the array
if(stringsArray != null) {
mStrings.addAll(toursArray);
}
}
}
}
My question is: can I call notifyDataSetChanged() from the onPostExecute function in the AsyncTask or at any other time when the AsyncTask has fetched the data?
解决方案can I call notifyDataSetChanged() from the onPostExecute function in the AsyncTask
Yes, you can call notifyDataSetChanged()
from onPostExecute
to Update Adapter data when doInBackground
execution complete. do it as:
@Override
protected void onPostExecute(ArrayList<String> stringsArray) {
//add the tours from internet to the array
if(stringsArray != null) {
mStrings.addAll(toursArray);
// call notifyDataSetChanged() here...
MyListAdapter.this.notifyDataSetChanged();
}
}
相关推荐
最新文章