Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android get activity returns null

I am using Action Bar on an Activity. For each Tab I am showing different layout. Since the layout is too heavy. So I am inflating each layout into a view. So on each Tab select

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    if (mView == null) {
        mView = LayoutInflater.from(mAct).inflate(mLayout, null);  // mAct is Activity reference
    }
    mAct.setContentView(mView);
    for (int i = 0; i < mFrags.length; i++) {
     mFrags[i] = (LutronFragment) mAct.getFragmentManager()
         .findFragmentById(mIds[i]);

     if (mFrags[i] != null) {
       mFrags[i].setupHeader();
      }
  }
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
  for (Fragment f : mFrags) {
   try { 
         if (f != null) {
        ft.remove(f);
      }
  } catch (IllegalStateException e) {
        e.printStackTrace();
  }
   }
}

So Now if I select tab second time and do some operation on that Tab, app get crashed on getActivity.(NullPointerException)

Please suggest if there is some another approach to cache heavy layout.

like image 522
Ashutosh Dubey Avatar asked Jul 18 '12 07:07

Ashutosh Dubey


2 Answers

The problem is most likely that you're using an old Fragment that has been detached from your Activity.

So, the first time you create your Fragment, it is attached to your activity. All is good. Then when you change tab, your fragment might or might not be detached from the activity. When you tab back to it, the old fragment may be detached from the activity and so getActivity() returns null.

This can happen if you're trying to keep references to your Fragments, rather than accessing them via the FragmentManager.

It can also happen if your adapter is returning a reference to a fragment rather than a new fragment. I've fallen into this trap.

(Posting the code where you create your fragments might help)

Edit

Maybe have a look at this and how they create add their ActionBar listeners. You need scope to your Activity. The way they do it is to define the listener in the Activity/Fragment (via implementing an interface) and then attach it to the Tab. This will give you scope and is probably a more stable way of doing things.

like image 60
Mike T Avatar answered Oct 18 '22 23:10

Mike T


This can happen if you create an anonymous object inside a fragment that calls getActiviy(). If getActivity() is called in the anonymous object after the fragment is popped off the fragment stack, getActivity() will return null. At that point, the fragment is no longer associated with an activity.

like image 34
Kru Avatar answered Oct 18 '22 23:10

Kru