如何从另一个类的AsyncTask onPostExecute()调用notifyDataSetChanged()

时间:2014-08-02 19:52:46

标签: android android-asynctask android-arrayadapter

在onCreate()中,我调用一个类ChannelStore来创建一个单例,我的片段的listview正在使用由channelstore创建的数据集。一旦doInBackground()完成,我需要在适配器上调用notifyDateSetChanged(),但我不知道如何实现我的AsyncTask在一个类(ChannelStore)中,并且适配器在我的片段(ChannelListFragment)中。有人能引导我找到解决方案吗?

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

ChannelStore中的AsyncTask:

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

    }

1 个答案:

答案 0 :(得分:0)

如果在onPostExecute中您可以访问由channelstore和适配器创建的数据集,则可以通过调用notifyDateSetChanged()来更改数据集并更新适配器。另一种方法是使用

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

在您需要访问ui线程以更新某些内容的每个位置。 您的onPostExecute始终在UI线程上运行,因此您可以访问您的片段适配器。为了做到这一点,你可以使用

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