Question

I have following code:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);    

        final RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
        int defaultValue = rg_numberOfQuestions.getId();
        RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(getPref(defaultValue, "NQ")));
        if(rbtn!=null)
            rbtn.setChecked(true);
        rg_numberOfQuestions.setOnCheckedChangeListener(this);

        final RadioGroup rg_numbersBetween = (RadioGroup) findViewById(R.id.radioGroupNumbersBetween);   
        int defaultValue1 = rg_numbersBetween.getId();
        RadioButton rbtn1 = ((RadioButton) rg_numbersBetween.findViewById(getPref(defaultValue1, "NB")));
        if(rbtn1!=null)
            rbtn1.setChecked(true);
        rg_numbersBetween.setOnCheckedChangeListener(this);     
    }   

As you can see there is repeat of same code twice which is this portion:

int defaultValue = rg_numberOfQuestions.getId();
        RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(getPref(defaultValue, "NQ")));
        if(rbtn!=null)
            rbtn.setChecked(true);
        rg_numberOfQuestions.setOnCheckedChangeListener(this);

Even though above code works fine my question is there a better way of doing this? As this seems i am repeating the code and as being new developer cant figure out any other way of doing this.

Was it helpful?

Solution

You could implement this method:

selectSavedRadioButton(RadioGroup group, String savedButtonPreferencesKey) {
    RadioButton button = (RadioButton) group.findViewById(getPref(group.getId(), preferencesKey));
    if (button != null) {
        button.setChecked(true);
    }
}

Which you can call like this:

RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
selectSavedRadioButton(rg_numberOfQuestions, "NQ");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top