Nisarg
Nisarg

Reputation: 407

Retrieving data with onSaveInstanceState via onCreate in Android

I'm creating an Android application that involves storing some data in a String ArrayList, which I'm calling "contentSpace." I need to save this array to retrieve the state of the app when it is started up again. For this, I'm using onSaveInstanceState, and passing it on to onCreate to retrieve the data. However, this is not working. Here is part of the code:

ArrayList<String> contentSpace = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main); 

    if (savedInstanceState != null) {

        contentSpace = savedInstanceState.getStringArrayList("Data");

        Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
    }

    else {

        Toast.makeText(this, "Failure", Toast.LENGTH_LONG).show();

    }


}


@Override
public void onSaveInstanceState(Bundle savedInstanceState) {

    super.onSaveInstanceState(savedInstanceState);

    if (contentSpace != null) {

    savedInstanceState.putStringArrayList("Data", contentSpace);

    Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();

    }

    else {

        Toast.makeText(this, "Not saved", Toast.LENGTH_LONG).show();

    }


}

When I run the program, Toast displays "Saved," so I suppose that contentSpace contains the data I need and is not null. However, when onCreate is called when I start the app again, Toast displays "Failure," supposedly indicating that contentSpace is null. Does anybody know does this make sense? Thank you in advance for your help.

Upvotes: 0

Views: 624

Answers (2)

zapekankaaa
zapekankaaa

Reputation: 82

As official reference says:

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

So try to replace there your code for extracting saved data and it will work.

public void onRestoreInstanceState(Bundle savedInstanceState) {...}

Upvotes: 0

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

However, when onCreate is called when I start the app again, Toast displays "Failure,"

That is because you are starting the activity again, onSaveInstanceState means that when you are recreating/pausing the view/activity (ex. screen rotation) it will call the onSaveInstanceState() method and then call the onCreate() which by then you'll get your data that was saved, but in your case data will not saved when you are trying to start the app again.

solution:

Use SharedPreferences instead to save data even if you quit the app.

Upvotes: 3

Related Questions