title: Correct way to save and restore a string at various Lifecycle points to an EditText using SharedPreferences?
body: <p>I didn't find a good definitive answer to this anywhere (maybe I'm bad at searching?)</p>
  <p>The android <a href="https://developer.android.com/reference/android/app/Activity.html#activity-lifecycle" rel="nofollow noreferrer">Activity Lifecycle</a> has various events that will cause a user to lose EditText contents unless you save and restore it during the lifecycle events - typically, using Shared Preferences. Sounds simple, but I can't get it working in practice; despite logging the EditText contents at each event it's not updating on my device when I navigate to another app and then back again.</p>
  <p>I have the user type a serial number in an EditText field. Here's what I'm doing in my activity:</p>
  <pre><code>private lateinit var sharedPref: SharedPreferences
  
  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      // (boilerplate databinding code omitted here)
      sharedPref = getPreferences(Context.MODE_PRIVATE)
  }
  
  private fun loadSN() {
      if(sharedPref.contains(PREFERENCE_SN)) {
          binding.serialNumberEditText.setText(sharedPref.getString(PREFERENCE_SN, &quot;&quot;))
          Log.d(TAG, &quot;serialNumberEditText is now ${binding.serialNumberEditText.text.toString()}&quot;)
      }
  }
  
  private fun saveSN() {
      Log.d(TAG, &quot;saveSN: saving ${binding.serialNumberEditText.text.toString()}&quot;)
      with (sharedPref.edit()) {
          putString(PREFERENCE_SN, binding.serialNumberEditText.text.toString())
          apply()
      }
  }
  
  override fun onStart() {
      super.onStart()
      loadSN()
  }
  override fun onPause() {
      super.onPause()
      saveSN()
  }
  
  override fun onStop() {
      super.onStop()
      saveSN()
  }
  override fun onResume() {
      super.onResume()
      loadSN()
  }
  override fun onRestart() {
      super.onRestart()
      loadSN()
  }
  </code></pre>
  <p>Sample log output when navigating to a different app then back again:</p>
  <pre><code>[navigate away from app]
  D/FooActivity: saveSN: saving ABCDE
  [^^ return to app here]
  D/FooActivity: serialNumberEditText is now ABCDE
  D/FooActivity: savePreference was called, restoring ABCDE
  D/FooActivity: serialNumberEditText is now ABCDE
  D/FooActivity: savePreference was called, restoring ABCDE
  D/FooActivity: serialNumberEditText is now ABCDE
  D/FooActivity: savePreference was called, restoring ABCDE
  </code></pre>
  <p>Yet it not restoring ABCDE to the EditText field. Why?</p>