我有一种奇怪的崩溃,我不时发现它。
崩溃是:Non-fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{com....../com......MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentManager com........MainActivity.getFragmentManager()' on a null object reference
android.app.ActivityThread.performLaunchActivity
崩溃的后盾是:
Caused by java.lang.NullPointerException
com.......adapters.MyRecyclerViewAdapter.<init>
com.......fragments.MyFragment.onCreate
android.app.Fragment.performCreate (Fragment.java:2242)
android.support.v7.app.AppCompatActivity.onCreate (AppCompatActivity.java:84)
com.........MainActivity.onCreate (MainActivity.java:223)
android.app.Activity.performCreate (Activity.java:6876)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)
现在代码是: 在Activity的onCreate中我使用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = this;
....
....
}
然后:
public static MainActivity getInstance() {
return mActivity;
}
然后我打开片段MyFragment:
mFragmentManager
.beginTransaction()
.addToBackStack("some key")
.add(R.id.container,
MyFragment.getFragment( ... ),
MyFragment.TAG).commit();
并在片段内部初始化RecyclerView适配器。 现在在适配器的构造函数中,崩溃发生在以下行中:
MainActivity.getInstance().getFragmentManager();
这意味着活动在某种程度上是空的,但是如果我们在回溯中看到活动的onCreate被调用并且MyFragment被添加到此活动的backstack中,怎么可能呢?
答案 0 :(得分:0)
替换代码
getActivity().getFragmentManager();
取代
MainActivity.getInstance().getFragmentManager();
希望这会起作用