Reloading data with SharedPreferences
Let's see how we can reload our data the next time the app is run. This code will reload the three values that the previous code saved. We could even declare our variables and initialize them with the stored values:
String username = prefs.getString("username", "new user"); int age = prefs.getInt("age", -1); boolean subscribed = prefs.getBoolean("newsletter-subscriber", false)
In the previous code, we load the data from disk using the method appropriate for the data type and the same label we used to save the data in the first place. What is less clear is the second argument to each of the method calls.
The getString
, getInt
, and getBoolean
methods require a default value as the second parameter. If there is no data stored with that label, it will then return the default value.
We could then check for these default values in our...