简体   繁体   English

从广播接收器更新片段中的列表视图

[英]Update a listview in a fragment from a broadcast receiver

I have to update a listview in a fragment if a file succesfully downloads. 如果文件成功下载,我必须更新片段中的列表视图。 So in my download manager's BroadcastReceiver I register this new broadcast receiver: 所以在我的下载管理器的BroadcastReceiver中,我注册了这个新的广播接收器:

Intent intent = new Intent();
intent.setAction("CONTENTS_NOTIFICATION");
context.sendBroadcast(intent);

And in my fragment in onCreateView I add the following code in order to register the receiver: 在onCreateView的片段中,我添加以下代码以注册接收器:

IntentFilter filter = new IntentFilter("CONTENTS_NOTIFICATION");
getActivity().getApplicationContext().registerReceiver(myReceiver, filter);

then: 然后:

private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            SQLiteDatabase db = DatabaseManager.getInstance(getActivity()).getWritableDatabase();
              c = SelectedExperience.getSelectedExperiences(db);

              String id_esperienza = "Selected Experience";

              if (c.getCount() != 0) {
                  id_esperienza = c.getString(c.getColumnIndex(SelectedExperience.ID_ESPERIENZA));
              }

            populateListview(v, id_esperienza);

        }
    };

and at the end: 最后:

public void onDestroyView() {
      super.onDestroyView();
      getActivity().getApplicationContext().unregisterReceiver(myReceiver);
}

I have to add two of these broadcast receivers for two different Fragment. 我必须为两个不同的片段添加两个这样的广播接收器。 On the first one, all works fine. 在第一个,一切正常。 If in the application the user is on the fragment, it updates, while on the second fragment I got these errors: 如果在应用程序中用户在片段上,它会更新,而在第二个片段上我得到了这些错误:

03-15 07:32:40.474: E/AndroidRuntime(1692): FATAL EXCEPTION: main
03-15 07:32:40.474: E/AndroidRuntime(1692): java.lang.RuntimeException: Error receiving broadcast Intent { act=CONTENTS_NOTIFICATION flg=0x10 } in sample.actionscontentview.fragment.ContentsFragment$1@418e0850
03-15 07:32:40.474: E/AndroidRuntime(1692):     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:768)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at android.os.Handler.handleCallback(Handler.java:725)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at android.os.Looper.loop(Looper.java:137)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at android.app.ActivityThread.main(ActivityThread.java:5191)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at java.lang.reflect.Method.invokeNative(Native Method)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at java.lang.reflect.Method.invoke(Method.java:511)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at dalvik.system.NativeStart.main(Native Method)
03-15 07:32:40.474: E/AndroidRuntime(1692): Caused by: java.lang.NullPointerException
03-15 07:32:40.474: E/AndroidRuntime(1692):     at sample.actionscontentview.fragment.ContentsFragment.populateListview(ContentsFragment.java:194)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at sample.actionscontentview.fragment.ContentsFragment.access$0(ContentsFragment.java:111)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at sample.actionscontentview.fragment.ContentsFragment$1.onReceive(ContentsFragment.java:107)
03-15 07:32:40.474: E/AndroidRuntime(1692):     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:758)
03-15 07:32:40.474: E/AndroidRuntime(1692):     ... 9 more

and the code is the same! 和代码是一样的! I can't get why it's not working. 我不明白为什么它不起作用。 It says there is a problem with populatelistView but the same function works fine inside the fragment if not called from the broadcast receiver. 它说populatelistView存在问题,但如果没有从广播接收器调用,则相同的功能在片段内工作正常。

The only difference I can think between this two fragments is that the one in which the update works is the first one opened when the application is launched. 我可以在这两个片段之间思考的唯一区别是更新工作的那个是在启动应用程序时打开的第一个片段。

Try using EventBus by GreenRobot https://github.com/greenrobot/EventBus 尝试使用GreenRobot的EventBus https://github.com/greenrobot/EventBus

When your file is succesfully downloaded you post an event 成功下载文件后,您即可发布活动

EventBus.getDefault().post(YourData.Downloaded);

Your fragment will register for receiving events, preferably in onStart() method 您的片段将注册接收事件,最好是在onStart()方法中

EventBus.getDefault().register(this);

And it will receive events in onEvent method: 它将在onEvent方法中接收事件:

public void onEvent(Data.State) {}

and then you can update your listview easily. 然后您可以轻松更新列表视图。 You also unregister from receiving events in onStop() method. 您还可以在onStop()方法中取消注册接收事件。 You can keep the data in your Application or stored. 您可以将数据保存在应用程序中或存储。 It is very easy and a nice solution. 这是一个非常简单的解决方案。 Hope it helps. 希望能帮助到你。 You can register as many fragments as you want for this event so once the EventBus posts the event, all available fragments registered for it will receive this event. 您可以为此事件注册任意数量的片段,因此一旦EventBus发布事件,为其注册的所有可用片段都将收到此事件。

I know this is old but in case you can help me out from your experience than please do at my issue: 我知道这已经过时了,但万一你可以帮我解决一下你的经历,而不是我的问题:

I have posted a similar question here: Broadcast receivers and Fragments . 我在这里发布了一个类似的问题: 广播接收器和片段 You can look for the workaround I did, although I think that there should be a better way of doing this. 你可以找到我做的解决方法,虽然我认为应该有更好的方法来做到这一点。

Some propose that all the broadcasts go to the Activity which is hosting the fragments and through a listener tell the fragments that they should update the view based on what has been received. 有人建议所有广播都转到托管片段的活动,并通过监听器告诉片段他们应该根据收到的内容更新视图。 This could be a better approach but it also could still involve null pointers checking for the view of the fragments. 这可能是一种更好的方法,但它仍然可能涉及检查片段视图的空指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM