For my quote creator app, if the user wrote a text in the app and by accident closed the app and started it again, all the text will be gone. I want ofcourse to prevent that, and I have tried a common solution without succses:
This is what I have done so far. I have removed unrelated code.
public static EditText mEditText;
private String savedText;
private static final String SAVED_TEXT_KEY = "";
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVED_TEXT_KEY, mEditText.getText().toString());
savedText = SAVED_TEXT_KEY;
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mEditText.setText(SAVED_TEXT_KEY);
String myString = savedInstanceState.getString(SAVED_TEXT_KEY);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.edittext);
mEditText.setTypeface(Style.getTypeface(this, Style.SERIF));
savedText = mEditText.getText().toString();
mEditText.setText(SAVED_TEXT_KEY);
if(savedInstanceState !=null){
savedText = savedInstanceState.getString(SAVED_TEXT_KEY);
}
}
Try this:
Save your state by override this:
and restore it:
If I am not wrong then you don't set the text on the textview again.
This should do the trick.
It seems to be that I had a wrong approach for this problem. As suggested I used SharedPreferences to save the current text.
First, you should give a proper key, not an empty string, for SAVED_KEY_TEXT.
Then, you should update your onCreate to this:
And your onRestoreInstanceState to this:
And at last your onSaveInstanceState to this:
Use IcePick Library :https://github.com/frankiesardo/icepick
@State String username; // This will be automatically saved and restored