How to receive an activity state instance(bundle) on request?

211 Views Asked by At

How to get the bundle that is given to this method on request (Bundle outState)?

@Override
protected void onSaveInstanceState(***Bundle outState***) {
    super.onSaveInstanceState(outState);

    // Only if you need to restore open/close state when
    // the orientation is changed
    if (adapter != null) {
        adapter.saveStates(outState);
    }
}
3

There are 3 best solutions below

0
On

It's the Bundle sent in the OnCreate method in your activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        savedInstanceState.getString("bla");
    }
}

Note that you'll have to check for null, because the first time you create your activity it will be null, since there was no previous state.

see https://developer.android.com/guide/components/activities/activity-lifecycle.html#oncreate for more information

1
On

You can get saved bundle back using below method:

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) {
// get your saved bundles back here
} 

Just refer this developer page, you will get clear idea about this

0
On

in Bundle instance you can pass the data and get it back in onCreate() method. like following

outState.putString("key1", "data1");
outState.putBoolean("key2", "data2");
outState.putInt("key3", "data3");

and in onCreate get it like following

if (savedInstanceState != null){
            data_1 =  savedInstanceState.getString("keys1");
            data_2 =  savedInstanceState.getBoolean("keys2");
            data_3 =  savedInstanceState.getInt("keys3");

}