Save the date!

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. Declare a field SharedPreferences prefs; at the top of our activity class.
  2. In onCreate, load the file:
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    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.

  3. In onDateSet, convert the deadline into millisecond format, put it into prefs and commit the transaction:
         .putLong("deadline", deadline.getTime())
  4. 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 updateUI().

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

Next: Animation