-4

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 ?

3 Answers3

1

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));
}
0

Using File Handling - I would suggest going basic by using a file handling technique. Auto create a text file using the java's InputStream and OutputStream classes. Then add the float inside it. As suggested in the comments above too.

Using properties files - Refer this code - http://www.mkyong.com/java/java-properties-file-examples/

Using a database - You can go ahead and use a database which will safely store the score and make sure no one tampers with it easily. Tutorial for this - http://www.tutorialspoint.com/jdbc/

Sanved
  • 921
  • 13
  • 19
0

Try simple with very few lines.

public void saveHighScore(File file, float highScore){
try{
Formatter out = new Formatter(file);
out.format("%f", highScore);
out.close();
}catch(IOException ioe){}
}
Francis Nduba Numbi
  • 2,499
  • 1
  • 11
  • 22