如何在for循环中将数据写入String

时间:2013-05-19 21:42:35

标签: java android string sqlite for-loop

所以基本上我有这个for循环的数据库。它每次都给出一个不同的分数,我需要保存到一个字符串(或文件,但我想一个字符串会更容易,因为我需要它在数据库的每次新调用时都是空的。)

我希望通过循环存储所有分数,然后在每个分数后添加一个(以保持它们分开)但我的代码不起作用,因为代码的一部分在for循环之外。我该如何解决?或者有更好的/其他方法来做我想要创建的东西吗?

DatabaseHandler db = new DatabaseHandler(camera.this);
List<Database> contacts = db.getAllContacts();
for (Database contact : contacts) {
    String test = contact.getMP();
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    printWriter.println(test);
}  
printWriter.flush();
printWriter.close();
return stringWriter.toString();

2 个答案:

答案 0 :(得分:4)

试试这个:

StringBuilder sb = new StringBuilder();
for (Database contact : contacts) { 
    if(sb.length > 0) {
        sb.append(", ");
    }
    sb.append(contact.getMP());
}
...
sb.toString();

答案 1 :(得分:1)

试试这个

DatabaseHandler db = new DatabaseHandler(camera.this);
List<Database> contacts = db.getAllContacts();
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
boolean first = true;
for (Database contact : contacts) {
   if(!first) printWriter.print(", ");
   else first = false;
   String test = contact.getMP();
   printWriter.print(test);      
}      
printWriter.flush();
printWriter.close();
return stringWriter.toString();

希望这有助于并享受您的工作