问题描述
我真的是Android新手,正在为Android编写一个简单的游戏。
在游戏中,就像在大多数游戏中都有分数一样,现在,我希望将分数保存在内部存储中,由于某种原因,我设法保存了分数,但没有将其重新加载。
这是代码:
final TextView best = (TextView) findViewById(R.id.best);
public int read = -1;
public StringBuffer buffer = new StringBuffer();
public String scoreTxt = buffer.substring(0, buffer.indexOf(" ") + 1);
public int score = 0;
// Save
try {
fileOutputStream = openFileOutput("record.txt", Context.MODE_PRIVATE);
fileOutputStream.write(scoreString.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Save() works fine", Toast.LENGTH_SHORT).show();
// load
try {
FileInputStream fileInputStream = openFileInput("record.txt");
while ((read = fileInputStream.read())!= -1){
buffer.append((char)read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
best.setText("Best: " + scoreTxt);
Toast.makeText(MainActivity.this, "load() is good too " + scoreTxt, Toast.LENGTH_SHORT).show();
当我运行该应用程序时,logcat中没有崩溃或任何特殊情况,但是当我使用scoreTxt
,输出什么都没有,只是“”。
有人可以帮我解决这个问题吗?
谢谢
1楼
您永远不会在代码中为scoreTxt分配值。
2楼
您需要在填充buffer
之后解析buffer
。现在,当scoreTxt
初始化时, buffer
为null
您需要更换它
best.setText("Best: " + scoreTxt);
与
scoreTxt = buffer.substring(0, buffer.indexOf(" ") + 1);
best.setText("Best: " + scoreTxt);
3楼
另外,我不会将游戏分数存储到文件中,因为分数经常变化,并且您要避免很多磁盘访问。 将其存储在SharedPreferences中,并不时将其刷新到后台线程上的文件中。