Skip to content Skip to sidebar Skip to footer

How To Hold The Selected Value In The Radio Button?

I'M doing quiz app. I have set 50 questions and each question contains 4 options(radio group) with pervious and next button. What i need is when select the answer and goes for next

Solution 1:

use SharedPreferences, that will save your values permanently, untill user reinstall (clear data) application. Shared Preferences works like this

// save string in sharedPreferencesSharedPreferencessettings= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editoreditor= settings.edit();
                    editor.putString("some_key", string); // here string is the value you want to save
                    editor.commit();                    

// restore string in sharedPreferences SharedPreferencessettings= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
string = settings.getString("some_key", "");

Solution 2:

Basically it looks like your problem is not how to set a radio button active, but the whole concept - so I describe how I'd do it:

The easy way

Use any kind of list or map (preferably hashmap, where the key is the question number and the value is the answer value (1,2 or 3 - simple integers)). Then when you're at question 2 for example, you check if there is alrerady an entry for the key 2, if so you you read out the value and actviate the corresponding radio button (this is by the way done with radio1.setChecked(true)) - if not as soon as the user clicks a radio button the anser is stored in the hash map.

The maybe better way :)

Almost same as before, but instead of simple "ints" as answers you use objects for your answers (maybe also for the questions, then you could store your answers directly in the question) - this is good if the answers / questions are gonna be more complicated then simple "1,2 or 3".

Side note

If the answers of the users should be available AFTER the app is closed, you'd have to store them in either a sqlite db or in shared preferences. I think sqlite is better for this, since these ansers are not really SharedPreferences/Settings, but you surely need a little more effort.


Since you ask for it:

switch(answer){
    case1:
        radio1.setChecked(true)
    break;
    case2:
        radio2.setChecked(true)
    break;
    case3:
        radio3.setChecked(true)
    break;
    default:
    break;
}

Post a Comment for "How To Hold The Selected Value In The Radio Button?"