1

So basically I have this database that is a for loop. It gives a different score every time, which I need to save to a String (or file, but I guess a string would be easier, because I need it to be empty at every new call for the database).

I want to store all the scores by going through the loop, and then adding a , after each score (to keep them seperate) but my code isn't working because a part of the code is outside the for loop. How do I fix this? Or are there better/other methods to do what I want to create?

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();
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
user1393500
  • 199
  • 1
  • 3
  • 16

2 Answers2

4

Try this:

StringBuilder sb = new StringBuilder();
for (Database contact : contacts) { 
    if(sb.length > 0) {
        sb.append(", ");
    }
    sb.append(contact.getMP());
}
...
sb.toString();
JamesB
  • 7,774
  • 2
  • 22
  • 21
1

Try this

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();

Hope this helps and enjoy your work

Marko Lazić
  • 883
  • 7
  • 9