user1410081
user1410081

Reputation:

can't save selected radio button to sharedpreferences

My problem is whenever I try to save what I input, specifically, checking appropriate answer in a radiogroup, everything else was saved but not the selected radiobutton in a group. Please see my code if I'm missing something. It's been days that this problem's driving me mad.

private void saveData(){

     //get entered value and set to a variable
     String fname_input = fnametext.getText().toString();
     int checkedButton = gendertext.getCheckedRadioButtonId();


     //SAVE shared pref value
     SharedPreferences.Editor editor = settings.edit();
     editor.putString("fname", fname_input);
     editor.putInt("gender", checkedButton);
     editor.commit();

     //show button after saving
     Toast.makeText(Profile_Pref.this, 
                "You have successfully saved!",
                Toast.LENGTH_SHORT)
                .show();

 } // end of saveData method

Thanks for help!

for my loadSavedData method: private void loadSavedData(){

    //RETRIEVE/load the saved shared pref value
     String fname = settings.getString("fname", null);

      fnametext.setText( fname );
      gendertext.setSelected(true);

 }   // end of loadSavedData method

I think there's a logic error here :(

Upvotes: 0

Views: 831

Answers (1)

RajV
RajV

Reputation: 7170

I am assuming gendertext is a RadioGroup.

The loadSavedData() needs to check the right radio button.

private void loadSavedData(){
    //RETRIEVE/load the saved shared pref value
    String fname = settings.getString("fname", null);

    fnametext.setText( fname );

    gendertext.check(settings.getInt("gender", 0));
}  

On a separate note, you shouldn't really store view IDs in preferences. They can change in future. Instead store gender values, like "M" and "F".

Upvotes: 1

Related Questions