Here is what I do when I save my score to the highscore.
public void save() {
try {
BufferedWriter fw = new BufferedWriter(new FileWriter(myDir
+ "/HIGHSCORE.txt"));
for (Integer i : scores) {
System.out.println(i);
fw.write(i);
fw.newLine();
fw.flush();
}
fw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void beforeSave() {
List<String> stringReader = new ArrayList<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(myDir + "/HIGHSCORE.txt"));
String s = "";
while ((s = br.readLine()) != null) {
System.out.println("LINE: " + s + "\n");
scores.add(Integer.parseInt(s));
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have two methods to save and load the data information, beforeSave() do I use in the onResume() mwthod, and save() have I put in the onPause(). It crash when I call the onStop()(shut down the program), And I’m prette sure that befoeStart() doesn’t work eather. I have use the Scanner class, to use the method nextInt(), but it doensn’t work :(. And when I just save one score, it workds. What on earth do I do wrong?
PS. I’m now sure if I have to use flush(), but it doesn’t work befoe eather.
//Daniel
Change
fw.write(i);tofw.write(i.toString());Rationale:
Currently your code saves values into a file in binary format but reads them in text format. You have to use the same format to fix the issue. Saving in text format makes reading highscores.txt much easier so I provided that solution.
Here’s my test code: