Restore edittext value while navigating activity

966 views Asked by At

I have a simple edittext on first activity and user enter some text and moves to second activity and from there to third and so on. Now when the user comes back to first activity the edit text should show him the text he enetered in the edittext.

SampleText= (EditText) findViewById(R.id.smpltxt);
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

Saving the value :

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);

  savedInstanceState.putString("MyString", SampleText);
}

Restoring the value :

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);

  String myString = savedInstanceState.getString("MyString");
}

I'm unable to get the text when he comes back to the first activity.

Can anyone say me what and where am I going wrong ?

3

There are 3 answers

3
Apoorv On

Replace

savedInstanceState.putString("MyString", SampleText);

with

savedInstanceState.putString("MyString", SampleText.getText().toString());

also check whether SampleText.getText()==null if so no need to add it.

0
flx On

I think the default behavior makes sure text in EditTexts is saved. Anyway: this is how to do it:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContent(/* your layout */);
  SampleText= (EditText) findViewById(R.id.smpltxt);

  if (savedInstanceState != null) {
    String myString = savedInstanceState.getString("MyString");
    SampleText.setText(myString);
  }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  savedInstanceState.putString("MyString", SampleText.getText().toString());
}
0
coder On

The answer is simple after a lot of hair pulling.

Added in onBackPressed() event of Activity2:

 public void onBackPressed() {
  finish();
 }