Aadesh Kulkarni Aadesh Kulkarni - 2 months ago 19
Android Question

onViewStateRestored crashing android app

I am a beginner in Android development. I wanted to save user login data so that he doesnt have to login after pausing and resuming the app or when he uses the app again. After going through some posts on stackoverflow, I realised onSavedInstance is the way to do it.

I have implemented the methods in one loginActivity but the app gives an error when i open this activity on the emulator.
the error is Unfortunately, 'Project_name' has stopped

So, I checked the log files, and got this

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Bundle.getBoolean(java.lang.String)' on a null object reference

on the line

boolean inSession = savedInstanceState.getBoolean("loggedin");

in the onViewStateRestored method.

Can someone help me find out where am i going wrong and Is there any better way to store login details so that user doesn't have to log in everytime the app goes in pause or stop mode?

Thanks for the help in advance. :)

public void onSaveInstanceState(Bundle savedInstanceState) {


public void onViewStateRestored(Bundle savedInstanceState) {

boolean inSession = savedInstanceState.getBoolean("loggedin");
if (inSession) {
String email = savedInstanceState.getString("email");
String pass = savedInstanceState.getString("password");
String type = "login";
BackgroundWorker bw = new BackgroundWorker(this.getContext());
bw.execute(null, pass, email, null, null, type);



According to android documentationWhen your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first

// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
    // Restore value of members from saved state
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
    // Probably initialize members with default values for a new instance


You should probably use Shared Preferences to store user login info