I have 5 checkboxes and I have to select multiple checkboxes.
I made a code like this to check check box is checked:
sports=(CheckBox)findViewById(R.id.sports_btn);
sports.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (sports.isChecked() == true)
list.add("4");
}
});
I am adding a value to an array list:
list ArrayList<String> list = new ArrayList<String>();
and I am retrieving the value as string like this:
StringBuilder sb = new StringBuilder();
for(int i =0; i < list.size(); i++)
{
for (String str: list)
{
sb.append(str.toString());
sb.append(",");
}
}
String sel_cat = sb;
I am getting the string but if two values are selected it is coming like 2,3, How to remove that last comma? I don't want the last comma the string has to be like 2,3.
append(String str) method appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument.
Append in Java is a StringBuilder and StringBuffer class method used to append a value to the current sequence. String concatenation in Java is done using the StringBuilder or StringBuffer class and append() method.
Append() in StringBuilder and StringBuffer There are 13 various overloaded append() methods in both StringBuffer and StringBuilder classes.
StringBuilder sb = new StringBuilder();
sb.deleteCharAt(sb.length()-1)
Or in your code, use
StringBuilder sb = new StringBuilder();
for(int i =0;i<list.size();i++)
{
String prefix = "";
for (String str : list)
{
sb.append(prefix);
prefix = ",";
sb.append(str);
}
}
String sel_cat = sb;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With