Alert Dialogebox with choice option and Display previouse selected value using sharedpreferences

use alertDialogebox with multiple option  where you need to select any one to make choice.

As well to get previous selected option value in alertDialogebox instead of default first selected option.   you need to store selected value into sharedpreference file ,and check each time  when you load this page .

like==>

class Alert extent Activity{

int j,m,savedState,languageLocalization;

public void onCreate(Bundle savedInstanceState) {

SharedPreferences();//check before loading layout
super.onCreate(savedInstanceState);
//
setContentView(R.layout.home_page1);

final CharSequence[] items = { “English”, “Hindi”,
“Marathi” };

AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
builder.setTitle(“Languages”);

builder.setCancelable(true);

/* even without making any choice it can be cancel .. otherwise use

setCancelable (false)  for compulsory selction*/

builder.setSingleChoiceItems(items, j,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
j = item;
SharedPreferences languageSelect = getSharedPreferences(
“MY_SHARED_PREF”, MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = languageSelect
.edit();

if (j == 0) {
CharSequence text = “English”;
Toast.makeText(getBaseContext(), text,
Toast.LENGTH_SHORT).show();
prefsEditor.putInt(“savedState”, j);
prefsEditor.commit();
SharedPreferences();
refresh();
}
if (j == 1) {
CharSequence text1 = “Hindi”;
Toast.makeText(getBaseContext(), text1,
Toast.LENGTH_SHORT).show();

prefsEditor.putInt(“savedState”, j);
prefsEditor.commit();
SharedPreferences();
refresh();
}
if (j == 2) {
CharSequence text2 = “Marathi”;
Toast.makeText(getBaseContext(), text2,
Toast.LENGTH_SHORT).show();
prefsEditor.putInt(“savedState”, j);
prefsEditor.commit();
SharedPreferences();
refresh();
}

}

});

builder.setNegativeButton(“cancel”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(),
Setting.class).setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(intent);
}
});

AlertDialog alert = builder.create();
alert.show();

}

private void SharedPreferences() {

SharedPreferences languageStateSave = getSharedPreferences(
“MY_SHARED_PREF”, MODE_PRIVATE);
languageLocalization = languageStateSave.getInt(“savedState”, 0);
//System.out.println(“Check Langauge    ” + languageLocalization);
m = languageLocalization;
System.out.println(“changed Lan:   ” + m);
j=m; //here we pass the previous selected value  which we use in alertDialogebox to set the selected choice….check “j” in alertDialogebox code

}

}

//you can find shared preferance file in data/data/application package folder/shared-prefs/