Getting Started in Android Development Part 30 - Reading SharedPreferences

North Border Software




Home Tutorials Hints & Tips About
Share on Facebook Share on Twitter

Getting Started in Android Development

Part 30 - Reading Shared Preferences

In this tutorial we will look at reading the shared preferences file created in the previous tutorial to change the background color of the PreferenceActivity and display the username.

An object of SharedPreferences called getData is declared:

SharedPreferences getData;

A private method is created called getSettings(). This is good practice as the settings will need to be read in the onCreate() and onResume() methods.

Within the getSettings() method, the first task is to read the preferences file:

getData = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);

The stored data can then be read and stored as string values. The getData() method is used and the "key" for the preference is passed. The second parameter is a default value that is used should the preference file not exist. In this example the defaults are "white" for the color and "nobody" for the username.

String colorText = getData.getString("color_key", "white");
String userText = getData.getString("user_key", "nobody");

The remaining code in the method is used the set the background color and TextView for the username.

The getSettings() method is called twice. Once in the onCreate() method when the app is first started and once in the onResume() method. If you refer back to the activity lifecycle in tutorial 1 you will see that the activity changes states. When the setting button is clicked the PreferanceActivity is paused. Therefore, when we resume the PreferenceActivity, the onCreate() method is not executed again. We need override the onResume() method to call getSetting() again. If we don't do this the username and background color will not be updated until the app is "destroyed" and started again.

Note the use of nested if else statements to set the background color. Android API levels prior to 19 (Kit Kat) used Java Development Kit 1.5 or 1.6. These JDK versions do not support switch and case statements with strings. Therefore, the nested if else statements are needed. If you plan to use minimum API of 19 or above then you can use a switch and case statement in place of the nested if else statements. Also note that the normal double equals (==) comparator is not used to test the condition in the if statement. It is necessary to use the equals() method.

After this tutorial your SettingsActivity.java file should look similar to the one below:


Download Download tutorial set 2


© 2015 North Border Software All rights reserved
Privacy and Cookies Terms of Use Disclaimer Copyright
North Border Software Logo

Android Apps and Training