Android开活动返回null [英] android get activity returns null

查看:163
本文介绍了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.

推荐答案

问题是最有可能是您使用的是旧片段已经脱离了您的活动。

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

所以,第一次创建您的片段,它是连接到你的活动。一切都很好。然后,当您更改标签,您的片段可能会或可能不会从活动的分离。当标签回吧,旧的片段可以从该活动分离等 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.

如果你想保持引用您的片段,而不是通过访问它们就会发生这种情况的 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.

(张贴在那里你创建你的碎片可能会帮助code)

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

修改

也许看看以及它们是如何创建添加他们的动作条的听众。您需要范围的活动。他们这样做的方式是定义监听器在活动/片段(通过实现一个接口),然后将其连接到标签。这会给你的范围,可能是做事更稳定的方式。

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天全站免登陆