Recipe Creating and Retrieving Shared Preferences

The shared preferences for an activity can be accessed using the getPreferences() method, which specifies the operating mode for the default preferences file. If instead multiple preference files are needed, each can be specified using the getSharedPreferences() method. If the shared preferences XML file exists in the data directory, it is opened; otherwise, it is created. The operating mode provides control over the different kinds of access permission to the preferences:

■ mode_private—Only the calling application has access to the XML file.

■ mode_world_readable—All applications can read the XML file.

■ mode_world_writeable—All applications can write to the XML file.

After a SharedPreferences object is retrieved, an Editor object is needed to write the name-value pairs to the XML file using the put() method. Currently, there are five primitive types supported: int, long, float, String, and boolean.The following code shows how to create and store shared preferences data:

SharedPreferences prefs = getSharedPreferences("myDataStorage",


Editor mEditor = prefs.edit();




The following shows how to retrieve shared preferences data:

SharedPreferences prefs = getSharedPreferences("myDataStorage",

MODE_PRIVATE); String username = prefs.getString("username", ""); String password = prefs.getString("password", "");

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment