List Array中的String Builder,如何在每个元素后添加空格/换行符?

时间:2011-12-14 16:43:33

标签: android arraylist stringbuilder

我已经从数据库列创建了一个数组列表,我想去除方括号并在新行中显示每个元素或间隔开。我正在使用字符串构建器来尝试执行此操作,此代码的问题在于它将所有元素添加到字符串中。任何人都可以帮我这个吗?

这是我的代码:

Cursor cursor2 = data.IngredientfetchRows(ID);
startManagingCursor(cursor2);
//cursor2.moveToFirst();

ArrayList<String> al = new ArrayList<String>();
cursor2.moveToFirst();
while(!cursor2.isAfterLast()) {
    //  Log.d("", "" + cursor.getString(cursor
    //                  .getColumnIndex(ProfileDbAdapter.KEY_PROFILE_NAME)));
    String mIngredientName = cursor2.getString(1);
    al.add(mIngredientName);
    cursor2.moveToNext();
}

StringBuilder builder = new StringBuilder();
for (String value : al) {
    builder.append(value);
}
String text = builder.toString();

Speech.setText(text);

data.close();
// + " " + cursor.getString(2) + "" + cursor.getString(3)
initSpeak();
speakButtons(StartSpeech);

3 个答案:

答案 0 :(得分:1)

如果您不介意列表末尾的换行符:

StringBuilder builder = new StringBuilder();
for (String value : al) {
    builder.append(value).append('\n');
}

答案 1 :(得分:0)

最简单的解决方案:

final static String BREAK = ", "; //Defined somewhere practical.

for (String value : al) {
    builder.append(value);
    builder.append(BREAK);
}

答案 2 :(得分:0)

你可以做这样的事情

StringBuilder builder = new StringBuilder();
      for (String value : al) {
             builder.append(value + " ");
          }
         String text = builder.toString();