Crea sito

Android: SharedPreferences Tutorial

What are SharedPreferences?

With this interface you can modify all that preferences that you want to store on phone.

For example you want to save if a user wants a feature activated or not, and a good

and simply way is characterized by SharedPreferences.

When you use your own sharedPreferences you have to use a String identifier for the preferencesName

and a mode to access them (for example Context.MODE_PRIVATE).

To read data from preferences you can read directly from preferences, pref.read(String identifier, default) ,

but to modify data you have to obtain an editor, apply the modifies and the commit them.

 

SDK-Android-Reference_for_SharedPreferences

 

Some examples:

//------get sharedPreferences

SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);

//-------get a value from them

pref.getString("NAME", "Android");

//--------modify the value

pref.edit().putString("NAME", "Simone").commit();

//--------reset preferences

pref.edit().clear().commit();

 

Discussion about posted project:

As you can see in the image at the beginning of this tutorial I have written a simply but articulated

activity to store and get some data about a person in a SharedPreferences.

String: Name, Surname

Integer: Age

In the code, that you can download from the link below, you will find:

- main.xml to manage the layout (3 edittext and 2 buttons to save and reset preferences)

- PreferenceConnector a class that simplify the interaction with SharedPreferences

- PreferencesActivity: the activity that is the engine for out simply app

With these three elements we recive inputs from user and we use SharedPreferences, related to our app

to store the recived data. In fact if you compile the three edittext and push save, when you enter a second

time in the app you will find the elements stored in the SharedPreferences (Reset to delete them all)

 

See you at the next tutorial,

Simone