android获取活动返回null [英] android get activity returns null

查看:31
本文介绍了android获取活动返回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();
  }
   }
}

所以现在如果我第二次选择选项卡并在该选项卡上执行一些操作,应用程序会在 getActivity 上崩溃.(NullPointerException)

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.

推荐答案

问题很可能是您正在使用与您的 Activity 分离的旧 Fragment.

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

因此,第一次创建 Fragment 时,它会附加到您的活动中.一切都很好.然后,当您更改选项卡时,您的片段可能会或可能不会与活动分离.当您返回到它时,旧片段可能与活动分离,因此 getActivity() 返回 null.

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.

如果您试图保留对 Fragment 的引用,而不是通过 FragmentManager 访问它们,就会发生这种情况.

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)

编辑

也许看看这个以及他们如何创建添加他们的 ActionBar 侦听器.您需要活动范围.他们这样做的方式是在 Activity/Fragment 中定义侦听器(通过实现一个接口),然后将其附加到 Tab.这将为您提供范围,并且可能是一种更稳定的做事方式.

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.

这篇关于android获取活动返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆