I have a simple game in which I would need to store a highscore (float) to a file and then read it next time the user goes on the app. I want it to be saved on the device, however, I have found no way to do that. How can I persist data on the device to a chosen location ?
You can use internal storage. This will create files that can be written to and read from. The best way to do this is to create a separate class that handles files. Here are two methods that will read and write the highscore.
To set the highscore, use setHighScore(float f).
public void setHighScore(float highscore){
FileOutputStream outputStream = null;
try {
outputStream = (this).openFileOutput("highscore", Context.MODE_PRIVATE);
outputStream.write(Float.toString(f)).getBytes());
outputStream.close();
} catch (Exception e) {e.printStackTrace();}
}
To get the highscore, use getHighScore().
public float getHighScore(){
ArrayList<String> text = new ArrayList<String>();
FileInputStream inputStream;
try {
inputStream = (this).openFileInput("highscore");
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr);
String line;
while ((line = bufferedReader.readLine()) != null) {
text.add(line);
}
bufferedReader.close();
} catch (Exception e) { e.printStackTrace();}
return Float.parseFloat(text.get(1));
}