0

我正在制作我的第一个 android 游戏。我想将用户名和分数保存到文件中并稍后读取。我正在尝试使用 arraylist 来存储 5 个用户对象。我不知道如何有效地写入文件和将其读回并存储在arraylist中。如果您知道另一种更好的方法,请告诉我。这是我用来写的方法。

public static void save(FileIO file) {
    preferences = file.getSharedPref();
    Editor editor = preferences.edit();
    for(int i=0;i<5;i++){
        editor.putString("username"+String.valueOf(i), User.userList.get(i).userName);
        editor.putInt("userscore"+String.valueOf(i), User.userList.get(i).highScore);
        }
    editor.commit();
}

这就是我用来阅读的方法。

public static void read(FileIO file) {
    preferences = file.getSharedPref();
    for(int i=0;i<5;i++){
        User.userList.get(i).userName=preferences.getString("username"+String.valueOf(i), "abc");
        User.userList.get(i).highScore=preferences.getInt("userscore"+String.valueOf(i), 0);
    }

}

这就是我试图显示我的高分的循环。 for(int i=0;i<5;i++){ g.drawString(String.valueOf(i+1)+"."+String.valueOf(User.userList.get(i).userName), 100, y, paint); g.drawString(String.valueOf(User.userList.get(i).highScore),150, y, paint2); y+=80; }

我收到 indexoutofbounds 异常

4

1 回答 1

3

当您希望存储值时:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Your_Activity.this);

Editor editor = sp.edit();
editor.putString("username", "<username goes here>");
editor.putInt("score", <the score goes here>);
editor.commit();   // Do not forget this to actually store the values

当您希望稍后阅读这些值时:

String gameUsername = sp.getString("username", "default");
int gameScore = sp.getInt("score", 0);

“用户名”和“分数”是他们推崇的价值观的关键。

SharedPreferences 是存储值时想到的最简单的方法。希望能帮助到你。~干杯。

于 2013-02-22T12:00:16.627 回答