Android dev primer: Shared Preferences – An Introduction

When you are into creating complex Android Applications, you will want the user to be able to customize the settings of your application according to his needs. Although not always, this is mostly where Shared Preferences are required in applications.

What are Shared Preferences?
When you need to save information across launches of your application with ease, you will be doing it with the help of Shared Preferences. It provides a way to preserve certain specific information even when your application is closed. It must however be remembered that it is definitely not the only way to do it. It is preferred over most other methods because it is predefined in Android for specifically this task alone.

In this post I’ll demonstrate the working of Shared Preferences. We will have an EditText in our activity. Once we write something in the EditText and close the application, in the subsequent launch of the application, the EditText will hold the same value. This is only the introduction as to how to use shared preferences and I will post about how to use it for cusomizable settings of an application. So start up an activity and follow along. Complete Source Code is at the bottom.

  • In the layout create an EditText.
  • Switch over to the java file and declare this EditText inside the class and outside all methods. We will be making it universally accessible because we will use it in more than one methods, as you will see shortly.
  • Inside the onCreate() method, get a reference to the EditText.
  • Now write the following lines in the onCreate() method.
    [java]
    SharedPreferences text = getSharedPreferences("mypref", 0);
    et.setText(text.getString("prefvalue", ""));
    [/java]
  • It is strongly advisable that you do not try to copy paste these lines and write them on your own. In the auto-complete suggestions of Eclipse IDE you will find small descriptions of the method signature and information about what this method does. It is necessary that you try and remember the function names.
  • Now, just like we’ve overridden the onCreate() method, we will override the onStop() method. This method is called when the activity is closed. Just as you start writing the onStop() method, make use of the auto-complete feature of Eclipse and well formatted method stub will appear.
  • Write the following lines inside the onStop() method.
    [java]
    super.onStop();
    SharedPreferences text = getSharedPreferences("mypref", 0);
    SharedPreferences.Editor editor = text.edit();
    editor.putString("prefvalue", et.getText().toString());
    editor.commit();
    [/java]
  • Save your work and execute it on an emulator/device.

Shared1

Understanding the Code

  • SharedPreferences holds the required information in the form of key-value pairs. Each key uniquely identifies a unit information or data.
  • While getting a reference to the SharedPreferences, we have made use of the function getSharedPreferences(String name, int mode). We have provided a name of mypref to the SharedPreference and a mode of zero. Remember that if a SharedPreference instance by this name does not exist already, Android creates one by this name.
  • To set the text of the EditText, we have made use of an overloaded version of setText() method. The signature for this method is setText(String key, String defValue). Here the key is the key for the key-value pair, as described in the first point. We have given it a value of prefvalue to it. defValue is the default value that appears if there does not yet exist a key-value pair where the key name is key, i.e prefvalue in this case.
  • Now, in order to store the text in the EditText in the SharedPreferences, we override the onStop() method because it is only when the activity is about to be closed that we need to save the text. We get a reference to the SharedPreferences by the name of mypref.
  • In order to be able to write something to the SharedPreferences we need a SharedPreference Editor. This is just like any other editor that allows writing of data.
  • With this editor, we now save the data to SharedPreferences by the help of putString(String key, String value) method. Remember, the key here should be the same as the one in the setText() method inside the onCreate() method, i.e. prefvalue in this case, the reason being that only then can the data we are saving, be uniquely identified.
  • Once we have told the editor what edits are required to be made, we want the editor to actually commit those changes on SharedPreferences, hence the commit() method.

COMPLETE SOURCE CODE

[java]
package com.nero.myfirstapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

EditText et;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);

SharedPreferences text = getSharedPreferences("mypref", 0);
et.setText(text.getString("prefvalue", ""));
}

@Override
protected void onStop() {
super.onStop();
SharedPreferences text = getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor = text.edit();
editor.putString("prefvalue", et.getText().toString());
editor.commit();
}

}

[/java]

Leave a Comment

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