0
我有一个应用程序在片段内的listview中显示新闻文章。 当第一次创建的片段,我启动一个线程,将通过API调用使用接口实现将线程结果返回给片段
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContext = getActivity();
new GetStoriesThread(mContext,this).start();
这两个片段和线程实现相同的接口从线通过数据获取的文章(故事)名单该片段
public interface GetStoriesThreadInterface {
public void onGetStoriesThreadResult(final ArrayList<Story> result);
}
之后线程完成处理,它会调用该接口的方法和数据传回调用片段。
问题
现在,当我得到片段中的结果,通过这个代码:
@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,这是一个完全不同的问题。
在此先感谢!
是的,我从工作线程中调用onGetStoriesThreadResult(),但我认为这是对接口的正确使用。 不是在Fragment类中调用的方法吗? –
显然不是 - 你从线程调用的任何东西都会在该线程中执行,并且不应该包含主线程使用的任何内存。 AsyncTask的onPreExecute和onPostExecute方法在主线程上运行,因此它们便于进行这种交互。 – kalinrj
我明白了。谢谢你的解释 ! –