user2709498
user2709498

Reputation:

How to save and retrieve variables upon screen rotation?

Can someone kindly give me a solution to this and explain how he/she came to that particular solution? Thanks so much

1) Upon rotation of the GUI from portrait to landscape or the opposite disappears all local variables.Write content of the class, where it is marked with To-Do, so that variable isGameFinished taken care of by rotation and collected again when the app is rotated

Class

public class StatteActivity extends Activity{

private boolean isGameFinished;
private Button buttonFinishGame;

protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_state);

//Get previous state for isGameFinished if it exists
//TO-DO

//Find button
buttonFinishGame = (Button) findViewByID(R.id.buttonFinishGame);
buttonFinishGame.setOnClickListener(new OnClickListener(){
public void onClick(View v){
isGameFinished = true;
}
});

if(isGameFinished){
finish();
}
}

protected void onSaveInstanceState(Bundle outState){
//To-Do
super.onSaveInstanceState(outState);
}
}

Upvotes: 2

Views: 1153

Answers (1)

LuckyMe
LuckyMe

Reputation: 3910

Do it like this:

@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    // Saving variables
    savedInstanceState.putBoolean("isGameFinished", isGameFinished);

    // Call at the end
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
    // Call at the start
    super.onRestoreInstanceState(savedInstanceState);

    // Retrieve variables
    isGameFinished = savedInstanceState.getBoolean("isGameFinished");
}

Cheers.

Upvotes: 2

Related Questions