[英]Save the value of an integer in a txt file in internal storage
我在做文字游戲。 我在代碼開頭聲明了“ public int x = 0
”。 x
的值控制着用戶的進度,故事的主要文本以及單選按鈕的文本。 我需要保存x
的值並能夠加載它,以便使用下面的代碼保存用戶進度。 我之前通過復制代碼進行了節省,但是它只是在加載時打印x的值以及故事的正文。
/*
Saves the game data
*/
String text = t.getText().toString();
try {
FileOutputStream fos = openFileOutput(TEXTFILE, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
t.setText("");
} catch (Exception e) {
e.printStackTrace();
}
/*
loads the game data
*/
try {
FileInputStream fis = openFileInput(TEXTFILE);
TextView t = (TextView) findViewById(R.id.mainText);
t.setText(null);
BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(fis)));
String line;
while ((line = reader.readLine()) != null){
t.append(line);
t.append("\n");
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//story logic
}else if (rb1.isChecked() && (x==2)){
t.setText("You put the key in your pocket");
} else if (rb2.isChecked()&& (x==2)) {
t.setText("You took the file");
為了存儲這樣的東西,您最好使用SharedPreferences
救:
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt("KEY", value);
加載:
int value = PreferenceManager.getDefaultSharedPreferences(context).getInt("KEY", defaultValue);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.