Using SharedPreferences in Android

Android has a mechanism which called preferences system for saving simple key-value pairs of primitive data types within applications. This mechanism works through SharedPreferences object. Preferences system stores data in xml file. If this file doesn’t exists Android will create automatically one. Preferences can be private or be accessible to other application. You can use it for storing some global application state and so on. It is very useful feature.

Here I am going to show example of using preferences. I will save data and retrieve it from preferences file.

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * Class which shows how work with preferences
 *
 * @author FaYnaSoft Labs
 */
public class Main extends Activity {
	public static final String PREFS_PRIVATE = "PREFS_PRIVATE";
	public static final String KEY_PRIVATE = "KEY_PRIVATE";

	private SharedPreferences prefsPrivate;

	private EditText editField;
	private Button  saveBtn;
	private Button  loadBtn;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		editField = (EditText) findViewById(R.id.firstId);
		saveBtn = (Button) findViewById(R.id.saveBtn);
		saveBtn.setText("Save");
		saveBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
				Editor prefsPrivateEditor = prefsPrivate.edit();
				prefsPrivateEditor.putString(KEY_PRIVATE, editField.getText().toString());
				prefsPrivateEditor.commit();
				editField.setText("");
			}
		});

		loadBtn = (Button) findViewById(R.id.loadBtn);
		loadBtn.setText("Load");
		loadBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
				editField.setText(prefsPrivate.getString(KEY_PRIVATE, "Empty"));
			}
		});
	}
}

I will explain.
PREFS_PRIVATE it is file which contains saved data. You can name it as you want.

For saving:

prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
Editor prefsPrivateEditor = prefsPrivate.edit();
prefsPrivateEditor.putString(KEY_PRIVATE, editField.getText().toString());
prefsPrivateEditor.commit();

This block of code gets preferences by file name. Sets data and saves it.

Fod loading:

prefsPrivate = getSharedPreferences(PREFS_PRIVATE, Context.MODE_PRIVATE);
editField.setText(prefsPrivate.getString(KEY_PRIVATE, "Empty"));

Here we open preferences and get our data using getString method.

Pay attention in second parameter in getSharedPreferences method. Second parameter is access level. Here I use MODE_PRIVATE – it allows to use this preferences only in this application.
There are others:
MODE_WORLD_READABLE – allows to other applications have read access to this file
MODE_WORLD_WRITEABLE – allows to other applications have write access to this file

You also can use:

getSharedPreferences(PREFS_PRIVATE, Context. MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

This hack allows to other applications have read and write access to your preferences file.

You can find preferences files at /data/data/your_package_name/shared_prefs

As you can see it is simple. Hope it was useful for you.

Help to make better articles. Leave a comment

Share

6 comments to Using SharedPreferences in Android

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna, tincidunt vitae molestie nec, molestie at mi. Nulla nulla lorem, suscipit in posuere in, interdum non magna.