Android getActivity()总是在片段内返回null

我遇到了一个奇怪的问题:getActivity()方法总是在fragment内部返回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() { 

……

这个callback被从另一个类中调用。

编辑2:

 class MemoryManager() { private OnDoneListener nDoneListener; public void setOnDoneListener(OnDoneListener onDoneListener) { this.onDoneListner = onDoneListener; } public void updateUiOnRequestFinish() { onDoneListener.onDone(); } } 

MemoryManaget本身调用updateUiOnRequestFinish()从一个不同的callback

编辑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} ` 

这对我来说很好。 所以我猜这个bug涉及到我从callback中调用getActivity()的方法。

Solutions Collecting From Web of "Android getActivity()总是在片段内返回null"