Android getActivity()始终在片段内返回null

时间:2013-04-08 12:37:18

标签: android android-fragments fragment android-fragmentactivity

我遇到一个奇怪的问题:getActivity()方法始终在片段内返回null。我在onAttach()和onCreateView()完成运行后调用它。

这个片段位于包含片段堆栈的FragmentActivity()内部,我向其添加片段的方式是:

(此代码是从Fragment Activity()的onCreate()调用的

SmartFragment fragment;
fragment = (SmartFragment) Fragment.instantiate(this,
fragmentClassName, params);     
mStackOfFragments.add(fragment);
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.add(R.id.tabcontent, fragment);
trans.addToBackStack(null);
trans.commitAllowingStateLoss();

我希望它足够清楚

编辑1:

对getActivity()的调用:

protected OnDoneListener nDoneListener = new OnDoneListener() {

    @Override
    public void OnDone(final int counter, final String name) {


        if (getActivity() != null)
            ((TabActivity) getActivity()).RunOnUiThread(new Runnable() {

...    ...

此回调是从另一个类调用的。

编辑2:

class MemoryManager()
{

    private OnDoneListener nDoneListener;

    public void setOnDoneListener(OnDoneListener onDoneListener)
    {
    this.onDoneListner = onDoneListener;
    }

    public void updateUiOnRequestFinish()
    {
      onDoneListener.onDone();
    }

}

MemoryManaget本身从另一个回调中调用updateUiOnRequestFinish()

编辑3:

FragmentManager日志是:

04-08 18:44:05.950: V/FragmentManager(16280): Commit: BackStackEntry{41f9bd60}
`04-08 18:44:05.950: D/FragmentManager(16280):   mName=null mIndex=-1 mCommitted=false
04-08 18:44:05.950: D/FragmentManager(16280):   Operations:
04-08 18:44:05.950: D/FragmentManager(16280):     Op #0: ADD FragmentMyProfile{41f9bc20 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): Setting back stack index 0 to BackStackEntry{41f9bd60}
04-08 18:44:05.950: V/FragmentManager(16280): Run: BackStackEntry{41f9bd60 #0}
04-08 18:44:05.950: V/FragmentManager(16280): Bump nesting in BackStackEntry{41f9bd60 #0} by 1
04-08 18:44:05.950: V/FragmentManager(16280): Bump nesting of FragmentMyProfile{41f9bc20 id=0x7f070126} to 1
04-08 18:44:05.950: V/FragmentManager(16280): add: FragmentMyProfile{41f9bc20 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): Allocated fragment index FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): moveto CREATED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:05.950: V/FragmentManager(16280): moveto ACTIVITY_CREATED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:05.990: V/FragmentManager(16280): moveto STARTED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
04-08 18:44:06.030: V/FragmentManager(16280): moveto RESUMED: FragmentMyProfile{41f9bc20 #0 id=0x7f070126}
`

对我而言看起来很好。所以我猜这个错误与我从回调中调用getActivity()的方式有关。

1 个答案:

答案 0 :(得分:7)

这个问题可以用于“android.app.Fragment”或“android.support.v4.app.Fragment”的getActivity()

如果您正在使用“android.support.v4.app.Fragment”,则需要检查是否未使用“android.app.Fragment”中的getActivity,反之亦然。