Android的呼叫从的AsyncTask notifyDataSetChanged(Android

2019-09-02 06:30发布

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?

Answer 1:

我可以调用notifyDataSetChanged()从的AsyncTask的onPostExecute功能

是的,你可以调用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();
    }
}


Answer 2:

呼叫notifyDataSetChanged()onPostExecute()作为

@Override
        protected void onPostExecute(ArrayList<String> stringsArray) {
            //add the tours from internet to the array
            if(stringsArray != null) {
                mStrings.addAll(toursArray);
MyListAdapter.this.notifyDataSetChanged();
            }
        }


Answer 3:

你尝试调用它在onPostExecute的方法ASyncTask 。 在onPreExecuteonPostExecute用于更新UI。



文章来源: Android call notifyDataSetChanged from AsyncTask