3

Can someone please explain why the value in my savedInstanceState is null? I have 3 widgets, an EditText, Button and TextView. The person types in what they want. The Phrase pops up in the TextView. I want to keep the input when I flip the phone. I tried saving the state but when the Activity is recreated, my Toast says that it's null:

public class MainActivity extends AppCompatActivity {
private EditText input;
private TextView output;
private Button button;
private String newString = "";

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

    input = (EditText)findViewById(R.id.input);
    output = (TextView) findViewById(R.id.output);
    button = (Button)findViewById(R.id.button);

    if (savedInstanceState!=null){
        Toast.makeText(this, "SAVED IS " + savedInstanceState.getString("example"), Toast.LENGTH_SHORT).show();
    }


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            newString = input.getText().toString();
            output.setText(newString);
        }
    });

}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    outState.putString("example",newString);
}}
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
Mark F
  • 1,523
  • 3
  • 23
  • 41

3 Answers3

4

You need to use this function onSaveInstanceState(Bundle outState), the one without PersistableBundle outPersistentState

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState, outPersistentState);
    outState.putString("example",newString);
}

void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState) this will only get called when you have attribute persistableMode specified in the activity tag inside manifest

You can read more about it here

Community
  • 1
  • 1
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
1

You can define a String variable that is global to your activity and define it upon restoringInstanceState.
Looks a little something like this:

String userInput;
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    userInput = savedInstanceState.getString("example") // Refers to your "outState.putString "example" <-- key
    output.setText(newString);
Montassir Ld
  • 531
  • 4
  • 12
1

Use below code it works for me.

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("example",newString);
    }
Maya Mohite
  • 675
  • 6
  • 8