Wai Yan Hein Wai Yan Hein - 6 months ago 15
Android Question

Data from savedInstanceState is always empty in Android

I am developing an Android app. I am testing using onSaveInstanceState event in activity. But it is not working as I expected. Cause value string is always empty when I retrieve it back onCreate event. Please see my scenario below.


This is my activity


@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("message","Hello world!");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null)
{
Toast.makeText(getBaseContext(),savedInstanceState.getString("message"),Toast.LENGTH_SHORT).show();
//Log.i("DATA_FROM_STATE",savedInstanceState.getString("message"));
}
}


When I run activity and change orientation, it is always toasting empty message. When I test uncommenting the Log line, it is giving me error cause data string is empty or null. Please why it is not working? Please how can i save and retrieve correctly. Please help me.

Answer

Wrong method override. Should use onSaveInstanceState(Bundle outState) and it will work. You can copy below snippet and test it.

public class MainActivity extends AppCompatActivity {

    private final String SAVED_MESSAGE_KEY = "SAVED_MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(savedInstanceState != null) {
            if(savedInstanceState.containsKey(SAVED_MESSAGE_KEY)) {
                Log.i("Saved message is:", savedInstanceState.getString(SAVED_MESSAGE_KEY));
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(SAVED_MESSAGE_KEY, "Hello world!");
    }
}