So do we put the deadline in outState and consider ourselves done? Well, we want to keep the deadline even if the entire phone is turned off, don’t we?

Instead, we’ll use SharedPreferences. This is essentially a glorified way to save small amounts of data in key:value format on disk. SharedPreferences survive practically everything except a factory reset (and even then we can choose to have it backed up by Google). Let’s try it out:

  1. Create a field prefs for our preferences. We can’t load it before onCreate, so we’ll use lazy loading to avoid loading prefs until we actually use it (at which time we know onCreate has been called):val prefs by lazy { PreferenceManager.getDefaultSharedPreferences(applicationContext) }Note: If you know that the preferences are only going to be used in this particular Activity, you can use this.getPreferences(MODE_PRIVATE) instead. Preference manager’s default shared preferences are shared across the entire app.
  2. In onDateSet, putthe deadline into prefs in millisecond format and commit the transaction:``` prefs.edit() .putLong(“deadline”, deadline.time) .apply();
  3. Read the deadline in onCreate using prefs.getLong and update our deadline field. Tip: System.currentTimeMillis() returns the current time in millisecond format, and could be a good candidate for a default value.

Fetching the deadline is nice and all, but shouldn’t we display it too? While we’re at it, what about making sure the time left is updated every time the app is presented onscreen, even if the activity is re-used?

This is the famous “Android Activity Lifecycle”, showing which methods of the Activity are called, and when it happens. In the lower left corner, we can see our onCreate() method, called once Android wants to create the activity. Whenever the app is about to become visible to the user, we can see that onStart() is called first.

  1. Override onStart(). Keep the call to super.onStart()
  2. Add a call to updateUI().

Run our app again. Now the correct deadline is displayed! Let’s finish up our app by adding the animation!

Next: Animation

LF