-1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Runkun Miao
  • 335
  • 1
  • 3
  • 14

1 Answers1

0

onPause always gets called when your activity loses focus. Be it a switch to another app, switching the activity, switching off the phone or whatsover.

When you press the back button, onPause gets called and the value of the sharedpreference gets saved. After that, onStop and onDestroy get called in the order written. Next time when the activity is created, you are fetching the saved sharedpref value, so it'll show up.

Akeshwar Jha
  • 4,516
  • 8
  • 52
  • 91