6.1 Android Shared Preferences

Android Shared Preferences Tutorial

 Android Shared preferences are different from preference API.  Preference APIs have role in user interfaces and Shared Preferences are used for storing small application data.  When we have small key-value pairs we use shared preferences. Let us study a brief introduction about shared preferences and then as usual we shall see an example implementation.

6.1.1 Introduction to Android Shared Preferences

 Android SharedPreference object points to a file. This file consists of the key-value pairs. This also provides methods for reading and writing. This can be private or shared and it is managed by the SharedPreference framework .We shall use Sharedpreference API to store and retrieve data.

There are two methods with which new SharedPreference file can be created or an existing file can be accessed and they are as follows: 

  1. getPreferences(): The default SharedPreference file is retrieved by this method. It is useful if only one shared preference is required in the activity.
  2. getSharedPreferences(): If multiple SharedPreference files are required which are to be identified by their respective names then this method should be used.

Other important methods are:

  • commit(): This is called to save the changes
  • edit(); By this method an editor is created which is of type SharedPreferences.Editor.
  • putInt(),putString(),putFloat() etc: These methods are used to pass the key value pairs.
  • getInt(),getString(), etc: These methods are used to read the SharedPreferences.

We don’t have large things to discuss as they can store key-value pairs. So let us implement an example and find out the working of shared preferences.

6.1.2 Android shared preferences Example

To demonstrate the usage of SharedPreferences we shall create an example. Open your IDE and create a project. Name it as you like. I am naming it as SharedPreferenceExample app. Open the xml file and code it as shown in the following listing:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:context=".MainActivity" >
        android:text="Hello Readers!!" />
        android:layout_marginTop="18dp" />
        android:text=" "
        android:textAppearance="?android:attr/textAppearanceMedium" />
        android:ems="10" >
        <requestFocus />
        android:text="OK" />

                                                               Figure - activity_main.xml file of Android Shared Preferences example

Corresponding graphical layout of app should be similar to the following snapshot:

Graphical layout of Android Shared Preferences example

                                                               Figure - Graphical layout of  Android Shared Preferences example

Now open the activity file of app and code it as shown in the following listing:

package com.android.tution.Preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
    private SharedPreferences prefs;
    private String prefName = "Mypreferences";
    private static final String KEY_FONT_SIZE = "font";
    private static final String KEY_TEXT_VALUE = "text";
    protected void onCreate(Bundle savedInstanceState) {
        final EditText edit = (EditText) findViewById(R.id.editText1);
        final SeekBar seek = (SeekBar) findViewById(R.id.seekBar1);
        final TextView tv = (TextView) findViewById(R.id.textView2);
        Button ok = (Button) findViewById(R.id.button1);
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putFloat(KEY_FONT_SIZE, edit.getTextSize());
                editor.putString(KEY_TEXT_VALUE, edit.getText().toString());
                        "Size of the font is saved successfully",
        SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        float fontSize = prefs.getFloat(KEY_FONT_SIZE, 14);
        seek.setProgress((int) fontSize);
        edit.setText(prefs.getString(KEY_TEXT_VALUE, " "));

                                              Figure-  First half of  Android Shared Preferences example code

Continue in the same activity. Second half of code is as shown in the following listing:

seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

                                                 Figure - Second part of  Android Shared Preferences example  code

So our last task is to go for the manifest file, please cross check it with the following listing:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >
        android:targetSdkVersion="18" />
        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

                                           Figure - manifest file of  Android Shared Preferences example

So we are done. Create a suitable emulator and run the application. In the output you have to enter a text in the edit text. Press the button saying ok and the same text would be loaded in the above text view which appears to be a blank space in your emulator. So the setup should look similar to the following snapshot:

Snapshot after first input

                                                                     Figure - Snapshot after first input

In our project, the font size is adjusted by the seek bar. For instance, scroll the seek bar towards your right hand side to increase the size of font and scroll towards left to minimize the size and vice versa. As you scroll the seek bar the text in edit text box would increase or decrease it’s font respectively.  A sample input is as shown in the following snapshot:

Figure - increasing the font size

                                                                               Figure - increasing the font size

Now to save this font size you have to press the button and a toast message would be prompted about the font selection. So output should be similar to the following snapshot:

Figure - Output after re-adjusting the size of font

                                                                     Figure - Output after re-adjusting the size of font

So buddies we are done. Congratulations on your success!! See you in the next section. Till then keep practicing. Happy App Developing!!