简体   繁体   English

Android内部存储错误

[英]Android internal Storage error

I am really new to android and writing a simple game for android. 我真的是Android新手,正在为Android编写一个简单的游戏。
In the game, like in most games you have score, now, I want the score to be saved in Internal Storage, and for some reason, I manage to save the score, but not load it back. 在游戏中,就像在大多数游戏中都有分数一样,现在,我希望将分数保存在内部存储中,由于某种原因,我设法保存了分数,但没有将其重新加载。
here is the code: 这是代码:

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();


when I run the app, there is no crash or anything special in the logcat, but when ever I use scoreTxt the output is nothing, just " ". 当我运行该应用程序时,logcat中没有崩溃或任何特殊情况,但是当我使用scoreTxt ,输出什么都没有,只是“”。
can somebody help me solve this problem? 有人可以帮我解决这个问题吗? Thanks 谢谢

您永远不会在代码中为scoreTxt分配值。

You need to parse buffer after it has being populated.Now when scoreTxt is initialized buffer is null 您需要在填充buffer之后解析buffer 。现在,当scoreTxt初始化时, buffer为null

You need to replace this 您需要更换它

 best.setText("Best: " + scoreTxt);

with

scoreTxt = buffer.substring(0, buffer.indexOf(" ") + 1);
best.setText("Best: " + scoreTxt);

In addition I wouldn't store game score into a file because score changes frequently and you want to avoid disk access a lot. 另外,我不会将游戏分数存储到文件中,因为分数经常变化,并且您要避免很多磁盘访问。 Store it in SharedPreferences and from time to time flush it to a file on a background thread. 将其存储在SharedPreferences中,并不时将其刷新到后台线程上的文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM