Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

android - Appending with StringBuilder

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...