Search code examples
androidandroid-asynctaskandroid-arrayadapter

How to call notifyDataSetChanged() from AsyncTask onPostExecute() in another class


In onCreate() I am calling a class ChannelStore to create a singleton and my fragment's listview is using that dataset created by channelstore. Once the doInBackground() finishes I need to call notifyDateSetChanged() on the adapter but I am not sure how to accomplish that being that my AsyncTask is in one class (ChannelStore) and the adapter is in my fragment (ChannelListFragment). Can someone lead me to the solution?

ChannelListFragment:

public class ChannelListFragment extends ListFragment {
    private static final String TAG = "ChannelListFragment";

    public ArrayList<Channel> mChannels;
    public ChannelAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.channels_title);
        setHasOptionsMenu(true);

        try {
            mChannels = ChannelStore.get(getActivity()).getChannels();
        } catch (XmlPullParserException | IOException | InterruptedException
                | ExecutionException | TimeoutException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        adapter = new ChannelAdapter(mChannels);
        setListAdapter(adapter);
    }
...

public class ChannelAdapter extends ArrayAdapter<Channel> {
        public ChannelAdapter(ArrayList<Channel> channels) {
            super(getActivity(), 0, channels);
        }

The AsyncTask in ChannelStore:

private class ChannelSetup extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
             // download xml feed

    }

    @Override
    protected void onPostExecute(String result) {
        try {
             // parse xml feed
        ....

        Log.i(TAG, "Adding programmes to channels...");
        addProgrammes(mProgrammes);

        Log.i(TAG, "Programmes per channel: "
                + listChannelsProgrammes(mChannels));

        // need to update listview adapter somehow

    }

Solution

  • If in onPostExecute you can access your dataset created by channelstore and your adapter, you can change your dataset and update your adapter by calling notifyDateSetChanged(). another way to do it is use

    runOnUiThread(new Runnable() {
       public void run() {
        // your code to update adapter.
       }
    });
    

    in every where that you need to access ui thread to update something. your onPostExecute always runs on UI thread so you have access your fragment adapter. in order to do that you can use

    getFragmentManager().getFragmentByTag('your fragment tag').ChannelAdapter.notifyDataSetChanged()