Retrieving Shared Preferences

Accessing Shared Preferences, like editing and saving them, is done using the getSharedPreferences method. Pass in the name of the Shared Preference you want to access, and use the type-safe get<type> methods to extract saved values.

Each getter takes a key and a default value (used when no value has yet been saved for that key), as shown in the Listing 6-2.

LISTING 6-2: Retreiving saved Shared Preferences

Available for download on public static String MY_PREFS = "MY_PREFS";

public void loadPreferences() { // Get the stored preferences int mode = Activity.MODE_PRIVATE;

SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, mode)

// Retrieve the saved values.

boolean isTrue = mySharedPreferences.getBoolean("isTrue", false); float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f); int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1); long aNumber = mySharedPreferences.getLong("aNumber", 0);

String stringPreference = mySharedPreferences.getString("textEntryValue", "");

Was this article helpful?

0 0
Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment