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”
2. Select Android build target
3. Enter application details
4. res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">SharedPreferencesDemo</string> <string name="str_btn_choose">Choose Android</string> </resources>
5. res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/tv_android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:padding="40dp" /> <Button android:id="@+id/btn_choose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/str_btn_choose" android:layout_gravity="center_horizontal" /> </LinearLayout>
- This is the layout file for the main activity
6. src/in/wptrafficanalyzer/sharedpreferencesdemo/Android.java
package in.wptrafficanalyzer.sharedpreferencesdemo; public class Android { static String[] code = new String[]{ "Jelly Bean", "Ice Cream Sandwich", "Honeycomb", "Gingerbread", "Froyo", "Eclair", "Donut", "Cupcake" }; }
- This class is used to statically store the list of Android versions
7. src/in/wptrafficanalyzer/sharedpreferencesdemo/AlertDialogRadio.java
package in.wptrafficanalyzer.sharedpreferencesdemo; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; 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(android.app.Activity activity) { super.onAttach(activity); try{ 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() { @Override public void onClick(DialogInterface dialog, int which) { AlertDialog alert = (AlertDialog)dialog; int position = alert.getListView().getCheckedItemPosition(); alertPositiveListener.onPositiveClick(position); } }; /** This is a callback method which will be executed * on creating this fragment */ @Override 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 */ b.setPositiveButton("OK",positiveListener); /** 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/MainActivity.java
package in.wptrafficanalyzer.sharedpreferencesdemo; import in.wptrafficanalyzer.alertdialogradio.AlertDialogRadio.AlertPositiveListener; import android.app.Activity; import android.app.FragmentManager; 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. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); OnClickListener listener = new OnClickListener() { @Override 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 */ alert.setArguments(b); /** Creating the dialog fragment object, which will in turn open the alert dialog window */ alert.show(manager, "alert_dialog_radio"); } }; /** Getting the reference of the textview from the main layout */ TextView tv = (TextView) findViewById(R.id.tv_android); /** 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(R.id.btn_choose); /** Setting a button click listener for the choose button */ btn.setOnClickListener(listener); } /** Defining button click listener for the OK button of the alert dialog window */ @Override 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 */ editor.commit(); /** Getting the reference of the textview from the main layout */ TextView tv = (TextView) findViewById(R.id.tv_android); /** 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
- 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.
10. Download

11. Reference
http://developer.android.com/guide/index.html

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in
You can hire me on hourly basis or on project basis for Android applications development.
For hiring me, please mail your requirements to info@wptrafficanalyzer.in.
My other blogs
store4js.blogspot.com