我知道这个问题很常见,我已经阅读了很多不同的答案,但没有一个适合我的问题。在我的应用程序中,我有一个活动,并且在 rye 活动中我加载了一个片段。我还向片段发送了一些数据(以 Bundle 的形式)。所以我的问题是当屏幕旋转时,我将片段保存在onSaveInstanceState
Activity 方法中并检查 onCreate 方法天气 savedInstance 是否为空,并在此基础上加载片段。活动代码:
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putParcelable(Const.TAG_REQ_CUSTOM,DetailsItems);
outState.putString(Const.TAG_FLOW, Const.TAG_MAIN_FLOW);
getSupportFragmentManager().putFragment(outState,"current_fragment",fragment);
}
onCreate 方法:
if (findViewById(R.id.fragment_frame) != null) {
if (savedInstanceState != null) {
// this invoke when screen rotate but the app crash
DetailsItems = savedInstanceState.getParcelable(Const.TAG_REQ_CUSTOM);
String flow = savedInstanceState.getString(Const.TAG_FLOW);
ft = getSupportFragmentManager().getFragment(savedInstanceState,"current_fragment");
mFragmentManager=getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
bundle= new Bundle();
bundle.putString(Const.TAG_FLOW, flow);
bundle.putParcelable(Const.TAG_REQ_BOOKING_DETAILS, bookingDetailsItems);
ft.setArguments(bundle);
mFragmentTransaction.replace(R.id.fragment_frame, ft).commit();
}else{
// load fragment on first time
}
}
所以我的问题是:我必须在哪里保存自定义对象(在父 Activity 或片段中)?当我保存的实例不为空时,应用程序崩溃和日志为:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference