Common issue with Android Programming.  The screen rotates and the data disappears.

Randolph Kaiser -
1 MIN READ
3

By default, when the screen is rotated your Activity is killed and restarted.  See the sample code below to save the state

 

Source:  http://stackoverflow.com/questions/5123407/losing-data-when-rotate-screen

 

//Use onSaveInstanceState(Bundle) and onRestoreInstanceState

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {

  // Save UI state changes to the savedInstanceState.  
 
// This bundle will be passed to onCreate if the process is 
 
// killed and restarted.

  savedInstanceState.putBoolean("MyBoolean", true); 
  savedInstanceState
.putDouble("myDouble", 1.9); 
  savedInstanceState
.putInt("MyInt", 1); 
  savedInstanceState
.putString("MyString", "Welcome back to Android");   
 
// etc. 
 
super.onSaveInstanceState(savedInstanceState); 
} 
//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("MyBoolean"); 
 
double myDouble = savedInstanceState.getDouble("myDouble"); 
 
int myInt = savedInstanceState.getInt("MyInt"); 
 
String myString = savedInstanceState.getString("MyString"); 
}

profile

Randolph Kaiser

Please Register or Login to post a reply

Replies