Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...