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:
- Declare a field
SharedPreferences prefs;at the top of our activity class.
- 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.
onDateSet, convert the deadline into millisecond format, put it into
prefsand commit the transaction:
prefs.edit() .putLong("deadline", deadline.getTime()) .apply();
- Read the deadline in
prefs.getLongand update our
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.
onStart(). Keep the call to
- Add a call
Run our app again. Now the correct deadline is displayed! Let’s finish up our app by adding the animation!