[英]Save the value of an integer in a txt file in internal storage
I am making a text game. 我在做文字游戏。 I have a "
public int x = 0
" declared at the start of my code. 我在代码开头声明了“
public int x = 0
”。 The value of x
is controlling the users progress and main text of the story as well as the text of the radio buttons. x
的值控制着用户的进度,故事的主要文本以及单选按钮的文本。 I need to save the value of x
and be able to load it in order to save the users progress using the code below. 我需要保存
x
的值并能够加载它,以便使用下面的代码保存用户进度。 I had the saving working before by copying the code but it was just printing the value of x along with the main text of the story on load. 我之前通过复制代码进行了节省,但是它只是在加载时打印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");
For storing something like this you'd be better using SharedPreferences 为了存储这样的东西,您最好使用SharedPreferences
Save: 救:
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt("KEY", value);
Load: 加载:
int value = PreferenceManager.getDefaultSharedPreferences(context).getInt("KEY", defaultValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.