I have an activity with two fragments. I am not using <fragment/> tags, I have two classes that extends Fragment, in that 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, I am receiving some broadcast receivers in activity from which some receivers update the UI from first fragment and some updates the UI from 2nd.
One of my broadcast receiver defined in my main acitivity is:
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 a view in it. But getting NPE.
here, when some broadcast receivers update the first fragment, it works properly, but when a broadcast receiver updates the 2nd fragment from activity, I get NPE.
My question is: How and where should I update the fragment? Should it be inside my activity? if yes then in which method? if not then where should I update the fragment?
Please help me!!!
Your activity logic should be separated from your fragments logic.
Your activity is supposed to handle the logic like:
But your activity is not supposed to handle this kind of logic:
It is the responsability of the fragment to update it’s content.
On the other hand, the activity may tell the fragment that it needs to update itself.
With that in mind, your fragments should expose methods like
OR
In your activity, when the
BroadcastReceiverreceives something you should:updateContent(With Blabla)method.OR
updateContent()method.Chose the most simple method according to your application business logic.