Android 重新启动加载程序调用时出错
我有一个片段,它将数据加载到列表适配器中以显示在屏幕上。当我的应用程序启动时,它会启动一个服务来寻找新的数据,如果找到了这些数据,片段将需要显示出来。目前,我的私人广播接收器实际上是在主要活动上,而不是片段上。这对我来说似乎不正确,但我看不出如何将来自广播接收器的通知在片段本身上传递回片段,我读到的另一个问题是建议这种方法 通过下面我发布的代码,当我的广播接收器收到一个通知并调用片段上的UpdateContent时,我得到了一个结果-我记录了以下错误:Android 重新启动加载程序调用时出错,android,Android,我有一个片段,它将数据加载到列表适配器中以显示在屏幕上。当我的应用程序启动时,它会启动一个服务来寻找新的数据,如果找到了这些数据,片段将需要显示出来。目前,我的私人广播接收器实际上是在主要活动上,而不是片段上。这对我来说似乎不正确,但我看不出如何将来自广播接收器的通知在片段本身上传递回片段,我读到的另一个问题是建议这种方法 通过下面我发布的代码,当我的广播接收器收到一个通知并调用片段上的UpdateContent时,我得到了一个结果-我记录了以下错误: 10-26 20:31:21.328: E
10-26 20:31:21.328: E/AndroidRuntime(711): FATAL EXCEPTION: main
10-26 20:31:21.328: E/AndroidRuntime(711): java.lang.RuntimeException: Error receiving broadcast Intent { act=updatedata flg=0x10 (has extras) } in com.thedailydigi.dailydigi.Main$1@41458418
10-26 20:31:21.328: E/AndroidRuntime(711): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:765)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.os.Handler.handleCallback(Handler.java:615)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.os.Looper.loop(Looper.java:137)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-26 20:31:21.328: E/AndroidRuntime(711): at java.lang.reflect.Method.invokeNative(Native Method)
10-26 20:31:21.328: E/AndroidRuntime(711): at java.lang.reflect.Method.invoke(Method.java:511)
10-26 20:31:21.328: E/AndroidRuntime(711): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-26 20:31:21.328: E/AndroidRuntime(711): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-26 20:31:21.328: E/AndroidRuntime(711): at dalvik.system.NativeStart.main(Native Method)
10-26 20:31:21.328: E/AndroidRuntime(711): Caused by: java.lang.IllegalStateException: There is already a listener registered
10-26 20:31:21.328: E/AndroidRuntime(711): at android.support.v4.content.Loader.registerListener(Loader.java:130)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.support.v4.app.LoaderManagerImpl$LoaderInfo.start(LoaderManager.java:260)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.support.v4.app.LoaderManagerImpl.installLoader(LoaderManager.java:510)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.support.v4.app.LoaderManagerImpl.createAndInstallLoader(LoaderManager.java:497)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.support.v4.app.LoaderManagerImpl.restartLoader(LoaderManager.java:643)
10-26 20:31:21.328: E/AndroidRuntime(711): at com.thedailydigi.dailydigi.activity.HorizontalListFragment.updateContent(HorizontalListFragment.java:130)
10-26 20:31:21.328: E/AndroidRuntime(711): at com.thedailydigi.dailydigi.Main$1.onReceive(Main.java:36)
10-26 20:31:21.328: E/AndroidRuntime(711): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:755)
问题的症结在于“由以下原因引起:java.lang.IllegalStateException:已经注册了一个侦听器”,但我没有注册一个侦听器
有人能解释一下吗
a) 为什么我目前得到上述错误,以及
b) 如果这是将附加数据加载到片段中的正确方法
我的相关课程的完整代码如下。谢谢你的帮助
Main.java
public class Main extends FragmentActivity {
private static final String LOG_TAG = "dd-Main";
private HorizontalListFragment mDailyDigiFragment;
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//TODO go update the UI from the database
int newRecords = intent.getIntExtra(DownloadFeedService.DOWNLOADED,0);
long date = intent.getLongExtra(DownloadFeedService.BEGIN_DATE, DownloadFeedService.NULL_DATE);
Log.d(LOG_TAG, newRecords + " new records downloaded!");
if (intent.getStringExtra(DownloadFeedService.KEY).equals(getString(R.string.daily_digi_short))) {
mDailyDigiFragment.updateContent(newRecords, date);
} else {
//TODO add our other fragments here
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(LOG_TAG, "Main Activity started");
registerReceiver(myReceiver, new IntentFilter(DownloadFeedService.UPDATEDATA));
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
//mDailyDigiFragment = HorizontalListFragment.newInstance(getString(R.string.daily_digi_short), 10, R.drawable.banner_dailydigi, true);
mDailyDigiFragment = HorizontalListFragment.newInstance(getString(R.string.daily_digi_short), 10, R.drawable.banner_dailydigi, true);
FragmentTransaction dailyDigiTransaction = getSupportFragmentManager().beginTransaction();
dailyDigiTransaction.add(R.id.dailydigi, mDailyDigiFragment).commit();
//TODO instantiate our other fragments here
/*
Fragment digiShowFragment = HorizontalListFragment.newInstance(getString(R.string.digi_show_short), 10, R.drawable.banner_digishow, true);
FragmentTransaction digiShowTransaction = getSupportFragmentManager().beginTransaction();
digiShowTransaction.add(R.id.digishow, digiShowFragment).commit();*/
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
HorizontaListFragment.java
public class HorizontalListFragment extends Fragment
implements LoaderManager.LoaderCallbacks<ArrayList<RssFeed.Article>> {
private ArticleAdapter adapter ;
private static final String LOG_TAG = "dd-HorizontalListFragment";
private static String MAX_LOAD_KEY = "max";
private static String DATASOURCE_KEY = "key";
private static String IMAGE_SRC_KEY = "image";
private static String SHOW_TEXT_OVERLAY = "showOverlay";
private String mRssFeedKey = "";
private int mDefaultLoad;
private int mImageResource = 0;
//TODO do we want to toggle the overlay on the digishow feed?
private boolean mShowTextOverlay = true;
private HorizontalListView mListView;
ArticleLoader mLoader;
public static HorizontalListFragment newInstance(String key, int max, int img, boolean showOverlay) {
HorizontalListFragment myFragment = new HorizontalListFragment();
Bundle args = new Bundle();
args.putString(DATASOURCE_KEY, key);
args.putInt(MAX_LOAD_KEY, max);
args.putInt(IMAGE_SRC_KEY, img);
args.putBoolean(SHOW_TEXT_OVERLAY, showOverlay);
myFragment.setArguments(args);
return myFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
mRssFeedKey = bundle.getString(DATASOURCE_KEY);
mDefaultLoad = bundle.getInt(MAX_LOAD_KEY, getResources().getInteger(R.integer.default_display_max));
mImageResource = bundle.getInt(IMAGE_SRC_KEY, 0);
mShowTextOverlay = bundle.getBoolean(SHOW_TEXT_OVERLAY, true);
mLoader = new ArticleLoader(getActivity(), mRssFeedKey,mDefaultLoad);
getActivity().getSupportLoaderManager().initLoader(0, null, this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.horizontal_list_section, container, false);
ImageView img = (ImageView) view.findViewById(R.id.Header_Image);
img.setImageResource(mImageResource);
mListView = (HorizontalListView) view.findViewById(R.id.hr_listview);
return view;
}
@Override
public Loader<ArrayList<RssFeed.Article>> onCreateLoader(int arg0, Bundle bundle) {
Log.d(LOG_TAG, "onCreateLoader: find " + mDefaultLoad + " articles from " + mRssFeedKey);
return mLoader;
}
@Override
public void onLoadFinished(Loader<ArrayList<RssFeed.Article>> arg0, ArrayList<RssFeed.Article> result) {
Log.d(LOG_TAG, "onLoadFinished with " + result.size() + " records from " + mRssFeedKey);
//update the listview with the combined results list
if (adapter == null) {
adapter = new ArticleAdapter(this.getActivity(), result,true);
mListView.setAdapter(adapter);
} else {
insertNewArticles(result);
adapter.notifyDataSetChanged();
}
//TODO use these methods to reset the list position ?
//mListView.setSelectionFromTop(currentFirstVisibleItem, 0);
//mListView.getFirstVisiblePosition();
}
@Override
public void onLoaderReset(Loader<ArrayList<RssFeed.Article>> arg0) {
Log.v(LOG_TAG, "onLoaderReset");
// TODO what do we need to do here?
}
public void updateContent(int newRecords , long date) {
if (date == DownloadFeedService.NULL_DATE) {
Log.d(LOG_TAG, "updateContent requesting " + newRecords + " new records.");
//this is when some new recent content has been downloaded
mLoader.setDownloadParameters(newRecords, 0);
getActivity().getSupportLoaderManager().restartLoader(0, null, this);
} else {
//this was probably downloaded cuz we're scrolling near the end
}
}
//both lists should already be sorted in date desc order
private void insertNewArticles(ArrayList<RssFeed.Article> listB) {
//TODO - we need to make sure we only add new entries
int listPosition = 0;
for (Article a : listB ) {
for (int i = listPosition; i < adapter.getCount(); i++) {
Article b = adapter.getItem(i);
//already in the list - skip over it
if (a.getInternalId() == b.getInternalId()) {
listPosition = i+1;
break;
}
//our new item is published after - it shows at the front of the list
if (a.getPublicationDate().before(b.getPublicationDate())) {
adapter.insert(a, i-1);
listPosition = i;
break;
}
}
//when we get to new items that pre-date our current list items, add them at the end
if (listPosition == adapter.getCount()) {
adapter.insert(a, listPosition);
listPosition++;
}
}
}
}
公共类HorizontaListFragment扩展了片段
实现LoaderManager.LoaderCallbacks{
专用适配器;
私有静态最终字符串LOG_TAG=“dd HorizontalListFragment”;
私有静态字符串MAX\u LOAD\u KEY=“MAX”;
私有静态字符串数据源\u KEY=“KEY”;
私有静态字符串IMAGE\u SRC\u KEY=“IMAGE”;
私有静态字符串SHOW\u TEXT\u OVERLAY=“showOverlay”;
私有字符串mRssFeedKey=“”;
私有int-mDefaultLoad;
私有int-mimagerource=0;
//我们想在digishow提要上切换覆盖吗?
私有布尔值mShowTextOverlay=true;
私有水平视图;
装载机;
公共静态HorizontaListFragment newInstance(字符串键、int max、int img、布尔showOverlay){
HorizontalListFragment myFragment=新的HorizontalListFragment();
Bundle args=新Bundle();
args.putString(数据源_键,键);
参数putInt(最大加载键,最大值);
args.putInt(IMAGE\u SRC\u KEY,img);
args.putBoolean(显示文本覆盖,显示覆盖);
myFragment.setArguments(args);
返回myFragment;
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Bundle=this.getArguments();
mRssFeedKey=bundle.getString(数据源\ U键);
mDefaultLoad=bundle.getInt(最大加载键,getResources().getInteger(R.integer.default\u display\u MAX));
mimagerource=bundle.getInt(IMAGE\u SRC\u键,0);
mShowTextOverlay=bundle.getBoolean(SHOW_TEXT_OVERLAY,true);
mLoader=newarticleloader(getActivity(),mRssFeedKey,mDefaultLoad);
getActivity().getSupportLoaderManager().initLoader(0,null,this);
}
@凌驾
已创建ActivityState上的公共无效(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图=充气机。充气(右布局。水平列表部分,容器,假);
ImageView img=(ImageView)view.findViewById(R.id.Header\u Image);
img.setImageResource(miImageResource);
mListView=(HorizontalListView)view.findViewById(R.id.hr\u列表视图);
返回视图;
}
@凌驾
公共加载器onCreateLoader(int arg0,Bundle){
Log.d(Log_标签,“onCreateLoader:从“+mRssFeedKey”中查找“+mDefaultLoad+”文章);
返回式装载机;
}
@凌驾
public void onLoadFinished(加载程序arg0,ArrayList结果){
Log.d(Log_标记,“onLoadFinished with”+result.size()+“记录来自”+mRssFeedKey);
//使用组合结果列表更新listview
if(适配器==null){
adapter=newarticleAdapter(this.getActivity(),result,true);
mListView.setAdapter(适配器);
}否则{
插入新文章(结果);
adapter.notifyDataSetChanged();
}
//如何使用这些方法重置列表位置?
//mListView.setSelectionFromTop(currentFirstVisibleItem,0);
//mListView.getFirstVisiblePosition();
}
@凌驾
公共void onLoaderReset(加载程序arg0){
Log.v(Log_标签,“onLoaderReset”);
//TODO我们需要在这里做什么?
}
public void updateContent(int newRecords,长日期){
if(date==DownloadFeedService.NULL\u日期){
Log.d(Log_标签,“updateContent请求”+newRecords+“newRecords”);
//这是最近下载的一些新内容
设置下载参数(newRecords,0);
getActivity().getSupportLoaderManager().restartLoader(0,null,this);
}否则{
//这可能是下载的,因为我们正在滚动接近尾声
}
}
//这两个列表应该已经按日期描述顺序排序
私有void insertNewArticles(ArrayList listB){
//TODO-我们需要确保只添加新条目
int listPosition=0;
(a条:清单B){
for(int i=listPosition;ipublic class ArticleLoader extends AsyncTaskLoader<ArrayList<RssFeed.Article>> {
private static final String LOG_TAG = "dd-ArticleLoader";
ArrayList<RssFeed.Article> mArticles;
final String mSource;
int mOffset = 0;
int mDownloadCount;
public ArticleLoader(Context context, String source, int max) {
super(context);
mSource = source;
mDownloadCount = max;
}
public void setDownloadParameters(int count, int offset) {
mOffset = offset;
mDownloadCount = count;
}
/**
* This is where the bulk of our work is done. This function is
* called in a background thread and should generate a new set of
* data to be published by the loader.
*/
@Override public ArrayList<RssFeed.Article> loadInBackground() {
Log.d(LOG_TAG, "loadInBackground: find " + mDownloadCount + " articles from " + mSource);
mArticles = ArticleManager.findArticles(getContext().getContentResolver(), mSource, mDownloadCount, mOffset);
return mArticles;
}
@Override
protected void onStartLoading() {
if(mArticles != null) {
deliverResult(mArticles);
} else {
forceLoad();
}
}
}
@Override
public Loader<ArrayList<RssFeed.Article>> onCreateLoader(int arg0, Bundle bundle) {
Log.d(LOG_TAG, "onCreateLoader: find " + mDefaultLoad + " articles from " + mRssFeedKey);
return mLoader;
}
@Override
public Loader<ArrayList<RssFeed.Article>> onCreateLoader(int arg0, Bundle bundle) {
Log.d(LOG_TAG, "onCreateLoader: find " + mDefaultLoad + " articles from " + mRssFeedKey);
return new ArticleLoader(getActivity(), mRssFeedKey,mDefaultLoad);
}