Java – Android call notifyDataSetChanged from AsyncTask

androidandroid-asynctaskbaseadapterjavalistadapter

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?

Best Solution

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();
    }
}