After studying how to use sharePreferences to store values in activity, I still have some questions about the way it stores data.
Since after we hit back button to close our activity, Android usually will call OnPause
, OnStop
and OnDestroy
. But in the way we use sharedPreferences, we call it inside OnPause method, like the code down below.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText)findViewById(R.id.editText);
mSharedPreferences = getSharedPreferences(PREFS, Context.MODE_PRIVATE);
mEditor =mSharedPreferences.edit();
String editTextString = mSharedPreferences.getString(EDIT_TEXT, "");
mEditText.setText(editTextString);
}
@Override
protected void onPause() {
super.onPause();
mEditor.putString(EDIT_TEXT, mEditText.getText().toString());
mEditor.apply();
}
In this case, I typed something and hit back button to back to exit the activity, when I go back to the activity. How android can still show what I typed in the EditText after activity got stopped and destroy.