Today, I'm talking about Shared Preferences. In this tutorial I'll talk about Shared Preferences and how to use it in application.
Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.
In order to use shared preferences, you have to call the method getSharedPreferences()
that returns a SharedPreference instance pointing to the file that contains the values of preferences.
SharedPreferences getSharedPreferences(String name, int mode);<br />
First parameter is the key and second parameter is the operating mode.
You can use the following modes:
- MODE_PRIVATE
MODE_WORLD_READABLE(deprecated in API level 17)MODE_WORLD_WRITEABLE(deprecated in API level 17)
MODE_PRIVATE
File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).
MODE_WORLD_READABLE
File creation mode: allow all other applications to have read access to the created file. Creating world-readable files is very dangerous, and likely to cause security holes in applications.
MODE_WORLD_WRITEABLE
File creation mode: allow all other applications to have write access to the created file. Creating world-readable files is very dangerous, and likely to cause security holes in applications.
You can save some data in the sharedpreferences by using SharedPreferences.Editor
class.
private final static String PREF_NAME = "pref_name";</p>
...
Editor editor = sharedpreferences.edit();
editor.putString(PREF_NAME, "test value");
editor.commit();
You also can use data for key from string.xml file:
private final static String PREF_NAME = "pref_name";
...
Editor editor = sharedpreferences.edit();
editor.putString(getString(R.id.pref_name), "test value");
editor.commit();
You can use following methods from Editor class:
apply()
- commit your preferences changes back from this Editor to the SharedPreferences object.clear()
- mark in the editor to remove all values from the preferences.commit()
- commit your preferences changes back from this Editor to the SharedPreferences object.putBoolean(String key, boolean value)
- set aboolean
value in the preferences editor.putFloat(String key, float value)
- set afloat
value in the preferences editor.putInt(String key, int value)
- set ainteger
value in the preferences editor.putLong(String key, long value)
- set along
value in the preferences editor.putString(String key, String value)
- set aString
value in the preferences editor.putStringSet(String key, Set<String> values)
- set aSet<String>
values in the preferences editor.remove(String key)
- mark in the editor that a preference value should be removed.
SharedPreference
let customise name of preference file and type of access (mode). When you are using DefaultSharedPreference
you name of shared preference file is PACKAGE_NAME of your application and file with preference accessible just for your application.
We finished with theoretical part. Next step is create a test application. This application will use SharedPreferences. In this tutorial I will use TextInputLayout
(you can read a tutorial about it).
First step is create a new project:
After it need to add dependency for using TextInputLayout in gradle file:
dependencies {
compile 'com.android.support:design:23.1.1'
}
After it need to add string constants to strings.xml
file in res/values
folder.
<string name="name_hint">Name</string>
<string name="age_hint">Age</string>
<string name="save_shared_preferences">Save (Shared Preferences)</string>
<string name="restore_shared_preferences">Restore (Shared Preferences)</string>
<string name="save_def_shared_preferences">Save (Default Shared Preferences)</string>
<string name="restore_def_shared_preferences">Restore (Default Shared Preferences)</string>
Next step is create layout for MainActicity
.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/name_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/name_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/name_hint"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/age_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/age_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/age_hint"/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/save_preference_button"
android:text="@string/save_shared_preferences"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/restore_preference_button"
android:text="@string/restore_shared_preferences"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/save_default_preference_button"
android:text="@string/save_def_shared_preferences"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/restore_default_preference_button"
android:text="@string/restore_def_shared_preferences"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
After it, we need to create a Person
class.
public class Person {
private String mName;
private int mAge;
public Person(String name, int age) {
this.mName = name;
this.mAge = age;
}
public String getName() {
return mName;
}
public void setName(String mName) {
this.mName = mName;
}
public int getAge() {
return mAge;
}
public void setAge(int mAge) {
this.mAge = mAge;
}
}
After it need to create methods for Save and Restore data. For it I created Utils
class. In this example I show how to use default shares preferences and shared preferences for certain name.
public class Utils {
private final static String MY_PREF = "my_pref";
private final static String NAME = "name";
private final static String AGE = "age";
public final static void saveSharedPreferences(Context context, Person person) {
SharedPreferences sharedPreferences = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(NAME, person.getName());
edit.putInt(AGE, person.getAge());
edit.commit();
}
public final static Person restoreSharedPreferences(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
Person person = new Person(sharedPreferences.getString(NAME, ""), sharedPreferences.getInt(AGE, -1));
return person;
}
public final static void saveDefaultSharedPreferences(Context context, Person person) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(NAME, person.getName());
edit.putInt(AGE, person.getAge());
edit.commit();
}
public final static Person restoreDefaultSharedPreferences(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Person person = new Person(sharedPreferences.getString(NAME, ""), sharedPreferences.getInt(AGE, -1));
return person;
}
}
Last step is updating MainActivity.java
file
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Person person;
private EditText mName;
private EditText mAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mName = (EditText) findViewById(R.id.name_editText);
mAge = (EditText) findViewById(R.id.age_editText);
findViewById(R.id.save_preference_button).setOnClickListener(this);
findViewById(R.id.save_default_preference_button).setOnClickListener(this);
findViewById(R.id.restore_preference_button).setOnClickListener(this);
findViewById(R.id.restore_default_preference_button).setOnClickListener(this);
}
@Override<br />
public void onClick(View v) {
switch (v.getId()) {
case R.id.save_preference_button:<
Utils.saveSharedPreferences(
this,
new Person(mName.getText().toString(), Integer.valueOf(mAge.getText().toString())));
break;
case R.id.save_default_preference_button:
Utils.saveDefaultSharedPreferences(
this,
new Person(mName.getText().toString(), Integer.valueOf(mAge.getText().toString())));
break;
case R.id.restore_preference_button:
person = Utils.restoreSharedPreferences(this);
mName.setText(person.getName());
mAge.setText(String.valueOf(person.getAge()));
break;
case R.id.restore_default_preference_button:
person = Utils.restoreDefaultSharedPreferences(this);
mName.setText(person.getName());
mAge.setText(String.valueOf(person.getAge()));
break;
}
}
}
You can open Android Device Monitor (Tools / Android / Android Device Monitor). After it choose DDMS and File Explorer tabs. You can find you application /data/data/package_name/ folder. As you can see you application had two different file with shared preferences.
Source code you can find on GitHub.