我真的是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时,输出什么都不是,只有“”。
有人能帮我解决这个问题吗?谢谢
发布于 2015-07-16 23:05:52
你永远不会在你的代码中给scoreTxt赋值。
发布于 2015-07-16 23:06:45
在初始化scoreTxt时buffer为populated.Now后,需要解析scoreTxt buffer为null
你需要换掉这个
best.setText("Best: " + scoreTxt);使用
scoreTxt = buffer.substring(0, buffer.indexOf(" ") + 1);
best.setText("Best: " + scoreTxt);发布于 2015-07-16 23:07:39
此外,我不会将游戏比分存储到文件中,因为比分经常变化,并且您希望避免大量访问磁盘。将其存储在SharedPreferences中,并不时地将其刷新到后台线程上的文件中。
https://stackoverflow.com/questions/31457766
复制相似问题