SharedPreferences Demo Application

July 6, 2012

In the article titled Alert Dialog Window with radio buttons in Android , we have seen that how to create an alert dialog window which contains radio buttons as options. In this article we are going to extend that application using shared preferences so that the data will not be lost on closing the application.

1. Create an Android project namely “SharedPreferencesDemo”

New Android Project

Figure 1 : New Android Project

2. Select Android build target

Select Android Target

Figure 2 : Select Android Target

3. Enter application details

Enter Application Details

Figure 3 : Enter Application Details

4. res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>

    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">SharedPreferencesDemo</string>
    <string name="str_btn_choose">Choose Android</string>


5. res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >



  • This is the layout file for the main activity

6. src/in/wptrafficanalyzer/sharedpreferencesdemo/

package in.wptrafficanalyzer.sharedpreferencesdemo;
public class Android {
    static String[] code = new String[]{
        "Jelly Bean",
        "Ice Cream Sandwich",
  • This class is used to statically store the list of Android versions

7. src/in/wptrafficanalyzer/sharedpreferencesdemo/

package in.wptrafficanalyzer.sharedpreferencesdemo;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

public class AlertDialogRadio  extends DialogFragment{

    /** Declaring the interface, to invoke a callback function in the implementing activity class */
    AlertPositiveListener alertPositiveListener;

    /** An interface to be implemented in the hosting activity for "OK" button click listener */
    interface AlertPositiveListener {
        public void onPositiveClick(int position);

    /** This is a callback method executed when this fragment is attached to an activity.
    *  This function ensures that, the hosting activity implements the interface AlertPositiveListener
    * */
    public void onAttach( activity) {
            alertPositiveListener = (AlertPositiveListener) activity;
        }catch(ClassCastException e){
            // The hosting activity does not implemented the interface AlertPositiveListener
            throw new ClassCastException(activity.toString() + " must implement AlertPositiveListener");

    /** This is the OK button listener for the alert dialog,
     *  which in turn invokes the method onPositiveClick(position)
     *  of the hosting activity which is supposed to implement it
    OnClickListener positiveListener = new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            AlertDialog alert = (AlertDialog)dialog;
            int position = alert.getListView().getCheckedItemPosition();

    /** This is a callback method which will be executed
     *  on creating this fragment
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        /** Getting the arguments passed to this fragment */
        Bundle bundle = getArguments();
        int position = bundle.getInt("position");

        /** Creating a builder for the alert dialog window */
        AlertDialog.Builder b = new AlertDialog.Builder(getActivity());

        /** Setting a title for the window */
        b.setTitle("Choose your version");

        /** Setting items to the alert dialog */
        b.setSingleChoiceItems(Android.code, position, null);

        /** Setting a positive button and its listener */

        /** Setting a positive button and its listener */
        b.setNegativeButton("Cancel", null);

        /** Creating the alert dialog window using the builder class */
        AlertDialog d = b.create();

        /** Return the alert dialog window */
        return d;

  • This is the DialogFragment class which creates AlertDialog window on executing the callback method “onCreateWindow()”

8. src/in/wptrafficanalyzer/sharedpreferencesdemo/

package in.wptrafficanalyzer.sharedpreferencesdemo;

import in.wptrafficanalyzer.alertdialogradio.AlertDialogRadio.AlertPositiveListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/** Since this class attaches the dialog fragment "AlertDialogRadio",
*  it is suppose to implement the interface "AlertPositiveListener"
public class MainActivity extends Activity implements AlertPositiveListener {
    /** Stores the share name for the sharedpreferences object */
String  share_name="ANDROID_VERSION";

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                /** Getting the fragment manager */
                FragmentManager manager = getFragmentManager();

                /** Instantiating the DialogFragment class */
                AlertDialogRadio alert = new AlertDialogRadio();

                /** Creating a bundle object to store the selected item's index */
                Bundle b  = new Bundle();

                /** Getting the sharedPreferences object to get the position, if already stored */
                SharedPreferences sharedPreferences = getSharedPreferences(share_name, 0);
                int position = sharedPreferences.getInt("position", 0);

                /** Storing the selected item's index in the bundle object */
                b.putInt("position", position);

                /** Setting the bundle object to the dialog fragment object */

                /** Creating the dialog fragment object, which will in turn open the alert dialog window */
      , "alert_dialog_radio");

        /** Getting the reference of the textview from the main layout */
        TextView tv = (TextView) findViewById(;

        /** Getting the previously selected version, if any , other wise 0 will be returned */
        int position = getSharedPreferences(share_name, 0).getInt("position", 0);

        /** Getting the reference of the button from the main layout */
        Button btn = (Button) findViewById(;

        /** Setting a button click listener for the choose button */

    /** Defining button click listener for the OK button of the alert dialog window */
    public void onPositiveClick(int position) {
        /** Opening the sharedPreferences object */
        SharedPreferences sharedPreferences = getSharedPreferences(share_name, 0);

        /** Opening the editor object to write data to sharedPreferences */
        SharedPreferences.Editor editor = sharedPreferences.edit();

        /** Storing the position value to the shared preferences */
        editor.putInt("position", position);

        /** Saving the values stored in the shared preferences */

        /** Getting the reference of the textview from the main layout */
        TextView tv = (TextView) findViewById(;

        /** Setting the selected android version in the textview */
        tv.setText("Your Choice : " + Android.code[this.position]);

  • This is the main activity file, from where the alert dialog window is invoked.

9. The application in execution

Main Activity

Figure 4 : Main Activity Screen

  • If the application is running for the first time, then the first item in the options list will be displayed in the main activity screen.
  • If the application already set a choice, then the item set in the previous attempt will be taken from the shared preference and will be shown in the main activity screen.
Choose An Option

Figure 5 : Choose An Option

The item selected from the alert dialog window is shown

Figure 6 : The item selected from the alert dialog window is shown

10. Download

11. Reference

How to hire me?

I am George Mathew, working as software architect and Android app developer at

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to

My other blogs

Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :

Tags: , , ,

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner