Java 使用接口实现将线程结果返回到片段
我有一个应用程序,它在一个片段内的列表视图中显示新闻文章。 当第一次创建片段时,我启动一个线程,该线程将通过API调用获取文章(故事)列表Java 使用接口实现将线程结果返回到片段,java,android,multithreading,android-fragments,interface,Java,Android,Multithreading,Android Fragments,Interface,我有一个应用程序,它在一个片段内的列表视图中显示新闻文章。 当第一次创建片段时,我启动一个线程,该线程将通过API调用获取文章(故事)列表 @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mContext = getActivity(); n
@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);
}
我知道使用getActivity().runOnUiThread(新的Runnable…
解决了这个问题,但我不明白为什么。有时getActivity()
返回null,这是一个完全不同的问题
谢谢!!
< p>你是从工作线程中调用了OnEntistReSeReultRead()吗?你不应该。考虑使用AsYcTebug代替裸线程,重写OnPixExtReUTE()方法,并从那里调用你的事件。< /P>是的,我正在调用OnEtStisteTraceReultReult()在工作线程中,但我认为这是接口的正确使用。该方法不是在Fragment类中调用的吗?显然不是-从线程调用的任何内容都会在该线程中执行,并且不应涉及主线程使用的任何内存。AsyncTask的onPreExecute和onPostExecute方法是n在主线程上,因此它们便于进行此类交互。我明白了。谢谢您的解释! @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.