Fragments and Broadcast Receivers

I have activity with two fragments . I do not use <fragment/> tags, I have two classes that extend Fragment , in this fragment I have:

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.bfragment, container, false); // this will inflate the Fragment in activity. } 

Now the problem is that I get several broadcast receivers in activity, from which some receivers update the user interface from the first fragment, and some update the user interface from the second.

One of my broadcast receivers, defined in my main characteristic:

 private BroadcastReceiver bcReceived = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { Log.d("", "BC Object Received"); ActionBar actionbar = getActionBar(); actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab bTab = actionbar.newTab().setText("B"); Fragment fragment = new BFragment(); bTab.setTabListener(new MyTabsListener(fragment)); actionbar.addTab(bTab, true); final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.bTable); // Getting null pointer exception here. linearLayout is not getting initialized. 

I want to use the above linearLayout and use it to inflate the view. But getting NPE.

here, when some broadcast receivers update the first fragment, it works correctly, but when the broadcast receiver updates the second fragment from activity, I get NPE.

My question is: How and where should the fragment be updated? Should it be inside my work? if so, in which method? if not, where should I update the fragment?

Please help me!!!

+6
source share
1 answer

The logic of activity must be separated from the logic of fragments.

Your activity should handle the logic as follows:

I need to display this fragment instead

But your activity should not handle this logic:

I need to update what's inside the fragment

The responsibility of the fragment is to update it. On the other hand, activity can tell a fragment that it should update itself.

With this in mind, your fragments should expose methods such as

 updateContent(With Blabla) 

OR

 updateContent() 

In your activity, when the BroadcastReceiver gets something, you should:

  • Check which fragment is currently displayed
  • Prepare content for update in fragment
  • Ask the fragment to update using the updateContent(With Blabla) method.

OR

  • Check which fragment is currently displayed
  • Ask the snippet to update itself using the updateContent() method.

Choose the easiest way according to the business logic of your application.

+25
source

Source: https://habr.com/ru/post/917858/


All Articles