LorenzoBerti LorenzoBerti - 2 months ago 8
Android Question

RadioGroup add RadioButton duplicate when standby phone android

I have a problem with

RadioGroup
and add dynamically
RadioButton

I have this function:

private void createRadio() {
RadioGroup rgp= (RadioGroup) findViewById(R.id.radioGroup);
RadioGroup.LayoutParams rprms;

for(int i=0;i<radios.length();i++){
RadioButton radioButton = new RadioButton(this);
try {
JSONObject object = radios.getJSONObject(i);
radioButton.setText(object.getString("name"));
radioButton.setId(object.getInt("id"));
rprms= new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
assert rgp != null;
rgp.addView(radioButton, rprms);
} catch (JSONException e) {
e.printStackTrace();
}
}
}


Where
radios
is a JSONArray that I retrieve from my db.
And my problem is that when I put in "stand by" my app, and so the activity is stopped when i reopen my activity I found the value of radiogroup duplicate.
Example:
if in my App have 3 radio button like:

1

2

3


When I stanby phone without close app, and reopen app after unlocked phone, i find this:

1

2

3

1

2

3


I Believe that the problem is the
rgp.addView
that add
radioButton
without check if radiobutton already exists.
There is a method for check if radioGroup is already populated?

Answer

You can do any of following:-

1) Remove all RadioButtons from RadioGroup before adding new ones as

    radioGroup.removeAllViews();

2) Check if RadioGroup is already populated

    boolean alreadyPopulated = radioGroup.getChildCount() > 0;