Vishnu Mohan
Vishnu Mohan

Reputation: 41

How to get the values of dynamically created checkbox android?

I created checkboxes dynamically(as response from api). Now I need to get the values of checkboxes those are checked. Here is my code.

private HashMap<Integer,String> answerMap= new HashMap<>();

for (int i = 1; i <= formsData.get(position).getValues().size(); i++) {
                CheckBox checkBox = new CheckBox(mContext);
                Forms forms = formsData.get(position);
                checkBox.setText(formsData.get(position).getValues().get(i - 1));
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            answerMap.put(formsData.get(position).getQuestionId(),checkBox.getText().toString());
                        } else {
                            answerMap.remove(formsData.get(position).getQuestionId());
                            System.out.println("map size: " + answerMap.size());
                        }
                        for (Map.Entry<Integer, String> entry : answerMap.entrySet()) {
                            Integer key = entry.getKey();
                            String value = entry.getValue();
                            System.out.println("question id : " + key + " answer : " + value);

                        }
                    }
                });  

but here if more than one checkbox is checked I'm only getting the value of last checked item. Anyone help me

Upvotes: 0

Views: 1330

Answers (1)

user8959091
user8959091

Reputation:

Create a list before your loop: ArrayList<CheckBox> array = new ArrayList<>();
After each creation of a checkbox add it to the list: array.add(checkBox);
Now you have all your checkboxes in the list and you can loop through them to find which are checked:

    for (int i = 0; i < array.size(); i++) {
        if (array.get(i).isChecked()) {
            Log.i("mine", i + " is checked");
        }
    } 

Upvotes: 2

Related Questions