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 that's 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 code and go about trying to obtain the real values. For example:

if (age == -1){
   // Ask the user for his age
}

We now know enough to save our user's settings in Note to Self.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.154.109