I am having trouble determining whether or not a certain tab has been selected in the navigation bar. I am trying to determine if the ingredient tab has been selected. Every time I run my code it returns that there is a null pointer error because mFragment is null and has not been instantiated.
Ok… I understand that mFragment is null. I guess this is where I am getting confused. When comparing fragments are you comparing their content or the object itself? And if anyone knows how to compare fragments that would be great. Thank you in advance. Here is the code:
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Bundle mTitleArgs;
private Fragment mFragment;
private IngredientCreation ingredientFrag;
private FragmentTabControl controller;
public TabListener(Activity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
ft.detach(mFragment);
ft.commit();
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ingredientFrag = (IngredientCreation) mActivity.getFragmentManager().findFragmentByTag("ingredients");
if (mFragment.equals(ingredientFrag)) {
System.out.println("got here");
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mTitleArgs);
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
}
The documentation on the ActionBar has a good example of how to properly create a Tab Listener. Checkout this link for a good implementation. http://developer.android.com/guide/topics/ui/actionbar.html