Skip to content Skip to sidebar Skip to footer

How To Save Radio Button State

am working on android application in which i open own custom dialog box and i use radio button in when i select radio button no doubt it selected and work but when i again open dia

Solution 1:

Add this

SharedPreferencessharedPreferences= PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
no.setChecked(sharedPreferences.getBoolean("no", false));
first.setChecked(sharedPreferences.getBoolean("first", false));
second.setChecked(sharedPreferences.getBoolean("second", false));
third.setChecked(sharedPreferences.getBoolean("third", false));

after

dialog.show();

Solution 2:

You should use Radio group and check its Radiobutton by ID. Like this on Create

 prefs = getSharedPreferences("LANG_PREFS", MODE_PRIVATE);
    rg = (RadioGroup)findViewById(R.id.language);
    rg.check(prefs.getInt("lang_btn_id", R.id.amharic));
    rg.setOnCheckedChangeListener(this);

and on onCheckedChanged of radio group use something like this

@OverridepublicvoidonCheckedChanged(RadioGroup radioGroup, int i) {
    Log.w("SettingActivity", "Radio Changed");
    SharedPreferences.Editoreditor= getSharedPreferences("LANG_PREFS", MODE_PRIVATE).edit();
    switch (radioGroup.getCheckedRadioButtonId()){
        case R.id.urdu:
            editor.putInt("lang_code", 0);
            editor.putString("lang_name", "ar");
            Log.d("Checked","urdu");
            break;
        case R.id.eng:
            editor.putInt("lang_code", 1);
            editor.putString("lang_name", "en");
            Log.d("Checked", "english");
            break;
        case R.id.amharic:
            editor.putInt("lang_code", 2);
            editor.putString("lang_name", "am");
            Log.d("Checked", "amharic");
            break;
    }
    editor.putInt("lang_btn_id", radioGroup.getCheckedRadioButtonId());
    editor.commit();

Post a Comment for "How To Save Radio Button State"