我基本上是尝试将mRecyclerView的当前状态保存到一个静态的Parcelable变量中,以确保其在onPause上安全,并将其恢复到mRcyclerView onResume。
这是我的静态变量的类:
public class MySavedState {
private static MySavedState ourInstance = new MySavedState();
private Parcelable state;
static MySavedState getInstance() {
if(ourInstance == null){
ourInstance = new MySavedState();
}
return ourInstance;
}
private MySavedState() {
}
public Parcelable getState() {
return state;
}
public void setState(Parcelable state) {
this.state = state;
}
}
这是我尝试设置值的行:
@Override
public void onPause() {
super.onPause();
Parcelable newState = mRecyclerView.onSaveInstanceState();
state.setState(newState);
}
错误消息:
java.lang.RuntimeException: Unable to pause activity {com.gunaya.tasmaew/com.gunaya.tasmaew.Controller.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gunaya.tasmaew.Model.MySavedState.setState(android.os.Parcelable)' on a null object reference
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3745)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3704)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3679)
at android.app.ActivityThread.access$1100(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gunaya.tasmaew.Model.MySavedState.setState(android.os.Parcelable)' on a null object reference
at com.gunaya.tasmaew.Controller.mListFragment.onPause(mListFragment.java:117)
还有一个额外的问题,我在调试器中始终显示此错误消息:
((Bundle)parce).mClassLoader = Cannot find local variable 'parce'
非常感谢您的陪伴。
答案 0 :(得分:1)
您的Singleton看起来不错,但看起来您没有找回它
MySavedState state = MySavedState.getInstance ();