调用了onSaveInstanceState,但是onCreate方法中的savedInstanceState抛出null

时间:2019-05-30 09:23:58

标签: android null onsaveinstancestate android-savedstate

将一些可序列化的值添加到saveinstancestate,但是saveInstanceState为null。在日志消息中调用onSaveInstanceState(),代码正确运行,但是在onCreate方法中,还原数据后将捕获空指针,并且保存的状态为null。类是正确的。 (可序列化)已设置。我找不到错误。感谢帮助。

@override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mb_activity);
            mBList = new ArrayList<MBClass>();
            mKList = new ArrayList<MKClass>();
            nAList = new ArrayList<AClass>();
            aList = new ArrayList<AClass>();
            try {
                mBList = (ArrayList<MBClass>) savedInstanceState.getSerializable("MBList");
                mKList = (ArrayList<MKClass>) savedInstanceState.getSerializable("MKList");
                aList = (ArrayList<AClass>) savedInstanceState.getSerializable("AList");
                nAList = (ArrayList<AClass>) savedInstanceState.getSerializable("NAList");

                Log.i("MB", "State geschrieben");

            } catch (NullPointerException ne) {
                //ne.printStackTrace();
                Log.i("MB", "State Null");
            }
    }
    @override    
    public void onSaveInstanceState(Bundle savedInstanceState) {
                savedInstanceState.putSerializable("MKList", (Serializable) mKList);
                savedInstanceState.putSerializable("MBList", (Serializable) mBList);
                savedInstanceState.putSerializable("NAList", (Serializable) nAList);
                savedInstanceState.putSerializable("AList", (Serializable) aList);
                super.onSaveInstanceState(savedInstanceState);
                Log.i("MB", "onSaveInstanceState");
            }

1 个答案:

答案 0 :(得分:0)

Serializable代替Parcelable对我有用。

@Parcelize // this annotation is needed in Kotlin. Not Sure about Java
class DataClass implements Parcelable {
   //Data members
}