I´ve been googling, I´ve looked at StackOverflow and see a lot of examples, but I can´t really get a hold of it. I´m new to android and learning how to read/write.
Maybe one of you can help me with some simple code. What I want is to save the score, time left and passed checkpoints in a file, since you can stop and play again days later.
So in my imagination, ideal would be (since it´s only simple data) not to work with SQL lite, but just with a textfile. I couldn´t really find examlpe code of how to work with a list, read, write.
It would be nice if you read an entire list (strings) from the file, this list can change in length. Then you can update the list, let´s say list[5]=200 (was 500) and then write it back to the file. Also you might want to add data to the file (the passed checkpoints).
As a start I came up with this, but I´m stuck with the checkpoints and am not sure if I write to the file the entire file will be rewritten or I´m adding data:
private static String filename = "currentgamedata.txt";
private String myDir = Environment.getExternalStorageDirectory() + "/MyDirectory/";
String enter = System.getProperty( "line.separator" );
public void WriteCurrentGameData(){
try {
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(openFileOutput( myDir+filename , MODE_WORLD_WRITEABLE)));
String MinutesLeft=Long.toString(GameTimeLeft);
String SaveScore=Integer.toString(score);
writer.write(MinutesLeft+enter);
writer.write(SaveScore+enter);
//HERE SHOULD COME SOME CODE FOR THE CHECKPOINTS
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ReadCurrentGameData(){
try {
BufferedReader input = new BufferedReader( new InputStreamReader(
openFileInput( myDir+filename )));
GameTimeLeft=Long.parseLong(input.readLine());
score=Integer.parseInt(input.readLine());
Log.d( "Reader" , Long.toString(GameTimeLeft) );
Log.d( "Reader" , Integer.toString(score) );
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Sorry, somhow the code doesn´t come out very beautifully. So summarized the questions:
Thanks a lot!
You have several options :
In any case, try to use a file format that simplifies further processing, for example you could use a Properties file (easy to write/parse in Java), and store each level checkpoint as a property or something like that (ie level_1_checkpoint=200).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.