Storing values as Preferences

Features

  • Store single values for later retrieval
  • Preference API in Android

SharedPreferences API

  • An Android API for storing and retrieving single values, often settings/preferences, in your app
  • Shared means that the values/preferences are shared between your own Activities
  • Preference classes (without Shared) is local to a single Activity
    • Less useful, most often stored values need to be shared between your Activities
  • Flag for MODE_
    • Controls if other apps can read the settings file or not
    • Should probably always be MODE_PRIVATE

Store single value

  • Get object that handles storing
    SharedPreferences.Editor pref = getSharedPreferences("MySettings", MODE_PRIVATE).edit();
    
  • Write one or more values to the store
    int value1 = 45;
    String value2 = "Mike";
    pref.putInt("count", value1);
    pref.putString("name", value2);
    
  • Remember to call commit, otherwise not saved!
    pref.commit();
    

Read a previously stored value

  • Get object that handles reading from store
    SharedPreferences pref = getSharedPreferences("MySettings", MODE_PRIVATE);
    
  • Retrieve stored value if it exists
    if (pref.contains("name")) {
      String value = pref.getString("name", "");
    }
    
  • No need to "commit" anything
  • A default value must always be specified to getXYZ, even if you've checked existance with contains

Simple String handling

  • Check if a String value does not exist
    String name = intent.getExtra("name");
    if (name != null) {
    }
    
  • Check if a String value is not empty
    if (name != null && name.length != 0) {
    }
    
  • Add one String value to another
    String firstname = "Mike";
    String lastname = "Smith";
    String fullname = firstname + " " + lastname;
    

Simple String conversion

  • Convert an Integer to a String
    int value = 1234;
    String text = Integer.toString(value);
    
  • Create a String from multiple values
    int value = 1234;
    String name = "Mike";
    String city = "London";
    String text = String.format("The value is %d for %s in %s", value, name, city);
    
  • Convert a String to an Integer
    String text = "1234";
    int value = Integer.parseInt(text);
    

More information

  • Book references
    • The Busy Coder's Guide 3.7
      • Using preferences, page 449