How to get set values in SharedPreferences in Android

Introduction
In this article I will explain how to insert and retrieve values from SharedPreferences in Android

Description
SharedPreferences in Android is used to store data in name/value pair which are available for lifetime of the application.

SharedPreferences class is used to get and set value in the SharedPreferences. SharedPreferences provides some put and get methods to insert and retrieve values in the SharedPreferences.

Adding values to SharedPreferences

To add values to SharedPreferences we have six put methods inside SharedPreferences.Editor class:

putString, putInt, putFloat, putLong, putBoolean, and putStringSet

Here, first five methods are used to store values of the respective data type and last method “putStringSet” is used to store a list of Strings using Set interface.

Example:

public void btnSavePreferences_Click(View vw)
{
	SharedPreferences prefs = getSharedPreferences("MyPrefs",
			Activity.MODE_PRIVATE);
	SharedPreferences.Editor editor = prefs.edit();
	editor.putString("email", "deepak.sharma009@gmail.com");
	editor.putInt("age", 27);
	editor.putBoolean("isMarried", true);
	editor.putFloat("temperature", 26.5f);
	editor.putLong("population", 1270272105);
	Set movies=new HashSet();
	movies.add("2012");
	movies.add("MI3");
	movies.add("Life of Pie");
	editor.putStringSet("movies", movies);
	Boolean flag = editor.commit();
	if(flag==true)
	{
		Toast.makeText(getApplicationContext(),
				"Preferences saved sucessfully!",
				Toast.LENGTH_LONG).show();
	}
}

Getting values from SharedPreferences

To get values from the SharedPreferences SharedPreferences class provides six get methods:

getString, getInt, getFloat, getLong, getBoolean and getStringSet

Example:

public void btnGetPreferences_Click(View vw)
{
	SharedPreferences prefs = getSharedPreferences("MyPrefs",
			Activity.MODE_PRIVATE);
	MsgBox("Email: "+prefs.getString("email", null));
	MsgBox("Age: "+prefs.getInt("age", 0));
	MsgBox("Marital status: "+prefs.getBoolean("isMarried", false));
	MsgBox("Temperature: "+prefs.getFloat("temperature", 0f));
	MsgBox("Population: "+prefs.getLong("population", 0));
	Set movies=new HashSet();
	movies=prefs.getStringSet("movies", null);
	if(movies!=null)
	{
		for(String movie:movies)
		{
			Toast.makeText(getApplicationContext(),
					movie,
					Toast.LENGTH_LONG).show();
		}
	}
}

SharedPreferences class resides inside android.content.SharedPreferences namespace. So you need to import this namespace before writing the code. Or you can use shortcut (Ctrl+Shift+O) to import all the missing namespaces referenced by the code.

2 thoughts on “How to get set values in SharedPreferences in Android

Leave a Reply

Your email address will not be published. Required fields are marked *