Android从AsyncTask调用notifyDataSetChanged
我有一个自定义ListAdapter,它在AsyncTask中从Internet获取数据。
数据完全添加到列表中,但是当我尝试执行操作时,应用程序崩溃了……
我确定这是因为我正在调用notifyDataSetChanged(); 在错误的时间(即在AsyncTask结束之前)。
我现在得到了什么:
public class MyListAdapter extends BaseAdapter { private ArrayList mStrings = new ArrayList(); public MyListAdapter() { new RetreiveStringsTask().execute(internet_url); //here I call the notify function **************** this.notifyDataSetChanged(); } class RetreiveStringsTask extends AsyncTask<String, Void, ArrayList> { private Exception exception; @Override protected ArrayList 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 stringsArray) { //add the tours from internet to the array if(stringsArray != null) { mStrings.addAll(toursArray); } } } }
我的问题是:我可以从AsyncTask中的onPostExecute函数或AsyncTask获取数据的任何其他时间调用notifyDataSetChanged()吗?
我可以从AsyncTask中的onPostExecute函数调用notifyDataSetChanged()
是的,当doInBackground
执行完成时,您可以从onPostExecute
调用notifyDataSetChanged()
来更新适配器数据。 这样做:
@Override protected void onPostExecute(ArrayList stringsArray) { //add the tours from internet to the array if(stringsArray != null) { mStrings.addAll(toursArray); // call notifyDataSetChanged() here... MyListAdapter.this.notifyDataSetChanged(); } }
在onPostExecute()
调用notifyDataSetChanged()
onPostExecute()
为
@Override protected void onPostExecute(ArrayList stringsArray) { //add the tours from internet to the array if(stringsArray != null) { mStrings.addAll(toursArray); MyListAdapter.this.notifyDataSetChanged(); } }
你试过在onPostExecute
方法中调用它ASyncTask
? onPreExecute
和onPostExecute
用于更新UI。