Search code examples
androidcheckboxstoring-data

Get and Store text from looped checkboxes into a String


I am kinda new in android and java programming, and I have a question, wish you could help me to solve it :)

I have a Program, it will fetch and loop data from database and convert it into some checkboxes, then user must check the checkboxes and hit the submit button,, The value(s) of the checked checkboxes will be stored to a String[], then will be send to another activity via Intent.putExtra..

So far, all I can do is fetch and loop the data from database, but I have no idea about how to store all the checked value (of the checkboxes) to string and sent it to another activity via intent. Can you guys please help me with this and where should I put the code?

And here is my code :

private void fetchFromDatabase() {
    // TODO Auto-generated method stub
    myDb.open();
    int totalGroup = myDb.countHowManyGroups(Username);
    String groupId[] = myDb.fetchGroupId(Username);
    String groupName[] = myDb.fetchGroupName(Username);
    String flag[] = null;
    for (int i = 0; i < totalGroup; i++) {

        listCheckBox = new CheckBox(this);
        listCheckBox.setText(groupName[i]);
        listCheckBox.setTag(groupId[i]);

        if (listCheckBox.isChecked()) {
            int x=0;
            flag[x]=listCheckBox.getText().toString();
            x++;
        }


        layout.addView(listCheckBox);
    }
    myDb.close();

    Button bSubmit = new Button(this);
    bSubmit.setText("Submit");
    layout.addView(bSubmit);

    bSubmit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (listCheckBox.isChecked()) {

            }

        }
    });
}

Solution

  • It depends of what you want to store. Do you want to store the id of the selected checkboxes? Then override their setOnCheckedChangeListener to save it's id on an array (remember that id is 0 unless you set it.)

    Do you want to save it's tag? Then override the same method but save the tag instead.

    Here is an example of the implementation of setOnCheckedChangeListener:

    List<String> myTagList = new ArrayList<String>();
    listCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                    myTagList.add(buttonView.getTag());
                else
                    myTagList.remove(buttonView.getTag());
            }
        });