Search code examples
javaandroidstaticparcelable

Setting value to static variable returns error


I basically try to save the current state of mRecyclerView into a static Parcelable variable to keep it safe onPause and restore it to the mRcyclerView onResume.

Here is my static variable's class:

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;
}

}

And here is the line where I try to set a value:

@Override
public void onPause() {
    super.onPause();

    Parcelable newState = mRecyclerView.onSaveInstanceState();
    state.setState(newState);


}

And the error message:

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)

And as an extra question, i keep having this error message in my debugger:

((Bundle)parce).mClassLoader = Cannot find local variable 'parce'

Thank you very much for your time guys.


Solution

  • Your Singleton looks OK but it looks like you are not retrieving it

    MySavedState state = MySavedState.getInstance ();