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 ...

Get Android Programming for Beginners - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.