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"
    xmlns:tools="http://schemas.android.com/tools"
    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"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Readers!!" />
    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="18dp" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/seekBar1"
        android:layout_marginTop="23dp"
        android:text=" "
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_centerVertical="true"
        android:ems="10" >
        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="16dp"
        android:text="OK" />
</RelativeLayout>

                                                               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";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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() {
            @Override
            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());
                editor.commit();
                Toast.makeText(getBaseContext(),
                        "Size of the font is saved successfully",
                        Toast.LENGTH_LONG).show();
                tv.setText(edit.getText().toString());
                tv.setTextSize(seek.getProgress());
            }
        });
        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, " "));
        edit.setTextSize(seek.getProgress());

                                              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() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub
                edit.setTextSize(progress);
            }
        });
    }
    @Override
    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"
    package="com.android.tution.Preferences"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.tution.Preferences.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

                                           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!!