0

我知道这个问题很常见,我已经阅读了很多不同的答案,但没有一个适合我的问题。在我的应用程序中,我有一个活动,并且在 rye 活动中我加载了一个片段。我还向片段发送了一些数据(以 Bundle 的形式)。所以我的问题是当屏幕旋转时,我将片段保存在onSaveInstanceStateActivity 方法中并检查 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
4

3 回答 3

1

你应该使用ViewModel. ViewModel是专门为此目的而制作的。

从文档:

ViewModel 是一个类,负责为 Activity 或 Fragment 准备和管理数据。它还处理 Activity / Fragment 与应用程序其余部分的通信(例如调用业务逻辑类)。

于 2017-09-28T12:28:13.857 回答
0

看看onRetainNonConfigurationInstance()getLastNonConfigurationInstance()

来自文档:

由系统调用,作为由于配置更改而销毁活动的一部分,当知道将立即为新配置创建一个新实例时。您可以在此处返回您喜欢的任何对象,包括活动实例本身,稍后可以通过在新活动实例中调用getLastNonConfigurationInstance()来检索这些对象。

于 2017-09-28T10:52:01.643 回答
0

在 Activity 中使用此代码:

    if (findViewById(R.id.fragment_frame) != null) {
        if (savedInstanceState != null) {
fragment =getSupportFragmentManager().getFragment(savedInstanceState,"current_fragment");

        }else{
           // load fragment on first time
        }
    }

在片段中:

//save custom object

 @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        outState.putParcelable("key",customObject);
    }

//now retrieve here

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null)
    customObject= savedInstanceState.getParcelable("key");
}
于 2017-09-28T12:22:36.220 回答