【问题标题】:Returning a thread result to the Fragment using interface implementation使用接口实现将线程结果返回到 Fragment
【发布时间】:2014-04-28 10:11:27
【问题描述】:

我有一个应用程序可以在片段内的列表视图中显示新闻文章。 首次创建片段时,我启动一个线程,该线程将通过 API 调用获取文章列表(Stories)

@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContext =  getActivity();

        new GetStoriesThread(mContext,this).start();

Fragment 和 Thread 都实现了相同的接口,用于将数据从线程传递到 Fragment

public interface GetStoriesThreadInterface {
    public void onGetStoriesThreadResult(final ArrayList<Story> result);
}

Thread处理完毕后,会调用接口方法,将数据传回给调用Fragment。

问题

现在当我在片段中得到结果时,通过这段代码:

    @Override
public void onGetStoriesThreadResult(final ArrayList<Story> result)
{
    if(result!=null)
    {
                mStoriesList.clear(); //mStoriesList is the list that i supply to the adapter of the ListView
                mStoriesList.addAll(result);
                adapter.notifyDataSetChanged(); //Exception here
    }
}

我得到以下异常:

04-28 18:03:58.432: E/ViewRootImpl(21513): com.says.news.Stories : Only the original thread that created a view hierarchy can touch its views.

我知道使用getActivity().runOnUiThread(new Runnable... 可以解决问题,但我不明白为什么。有时getActivity() 返回null,这是一个完全不同的问题。

提前致谢!!

【问题讨论】:

    标签: java android multithreading android-fragments interface


    【解决方案1】:

    您是从工作线程中调用 onGetStoriesThreadResult() 吗?你不应该。考虑使用 AsyncTask 而不是裸 Thread ,覆盖 onPostExecute() 方法并从那里调用您的事件。

    【讨论】:

    • 是的,我从工作线程中调用 onGetStoriesThreadResult(),但我认为这是对接口的正确使用。方法不是在 Fragment 类中被调用吗?
    • 显然不是 - 无论您从线程调用什么都会在该线程中执行,并且不应该涉及您的主线程使用的任何内存。 AsyncTask 的 onPreExecute 和 onPostExecute 方法在主线程上运行,因此它们对于此类交互非常方便。
    • 我明白了。谢谢你的解释!
    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 2014-02-19
    • 2013-11-23
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多