How to Save State of Activity in Android

Posted on .

This is very simple and asked everywhere like interviews and during our LIVE projects . Lets explore .

METHOD – 1

You need to @ override

onSaveInstanceState(Bundle savedInstanceState)

and note down your application values which you want to save eg:

@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{super.onSaveInstanceState(savedInstanceState);// Save UI state changes to the savedInstanceState.// This bundle will be passed to onCreate if the process is// killed and restarted.
  savedInstanceState.putBoolean("AndroidBoolean",true);
  savedInstanceState.putDouble("AndroidDouble",1.9);
  savedInstanceState.putInt("AndroidInt",1);
  savedInstanceState.putString("AndroidString","Welcome back to Android Arena");// etc.}

Bundle stores values in the form of (Name-Value-Pair) map . It is passed in onCreate() . The values can be extracted through onRestoreInstanceState() .

@Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);// Restore UI state from the savedInstanceState.// This bundle has also been passed to 
onCreate.boolean myBoolean = savedInstanceState.getBoolean("AndroidBoolean");
double myDouble = savedInstanceState.getDouble("AndroidDouble");
int myInt = savedInstanceState.getInt("AndroidInt");
String myString = savedInstanceState.getString("AndroidString");}

 

 METHOD – 2

Instead of saving data in

savedInstance()

you can use methods like

onpause() ,onResume()

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *