Android从AsyncTask调用notifyDataSetChanged

Han*_* Vn 0 java android listadapter android-asynctask baseadapter

我有一个自定义ListAdapter,它在AsyncTask中从Internet获取数据.

数据完全添加到列表中,但是当我尝试执行操作时,应用程序崩溃了......

我确定这是因为我正在调用notifyDataSetChanged(); 在错误的时间(即在AsyncTask结束之前).

我现在得到了什么:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我可以从AsyncTask中的onPostExecute函数或AsyncTask获取数据的任何其他时间调用notifyDataSetChanged()吗?

ρяσ*_*я K 5

我可以从AsyncTask中的onPostExecute函数调用notifyDataSetChanged()

是的,您可以在执行完成时notifyDataSetChanged()onPostExecute更新适配器数据调用doInBackground.这样做:

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)