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:
val username = prefs.getString( "username", "new user") val age = prefs.getInt("age", -1) val subscribed = prefs.getBoolean( "newsletter-subscriber", false)
In the previous code, we load the data from disk using the function 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 function calls.
The getString
, getInt
, and getBoolean
functions require a default value as the second argument. 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 code and go about trying to obtain the required values or handling an error...