【问题标题】:Save Basic Statistics data?保存基本统计数据?
【发布时间】:2018-04-09 16:19:45
【问题描述】:

我正在制作一款需要将一些统计数据保存到内存中的游戏(已玩的游戏、赢得的游戏等)。 我曾尝试使用 sharedpreferences,但据我所见,文档似乎很差,而且我无法让它工作。 我错过了什么吗?

try {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        SharedPreferences stats = getPreferences(MODE_PRIVATE);
        CharSequence gampjla = "Games played: " + stats;
        Toast toast = Toast.makeText(context, gampjla, duration);
        toast.show();

        gamesPlayed++;
        SharedPreferences.Editor editor = stats.edit();
        editor.putInt("gameplay", gamesPlayed).commit();
        CharSequence gampla = "Games played: " + gamesPlayed;
        Toast toayst = Toast.makeText(context, gampla, duration);
        toayst.show();

    }
    catch (Exception e) {
            Context context = getApplicationContext();
            CharSequence errormsg = "Unable to save!! " + e;
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, errormsg, duration);
            toast.show();
    }

我尝试了变化,但没有任何效果! 感谢您的帮助!

编辑:一些变量名中的随机字母是因为我想要一个不同的变量名进行测试,并且因为我感到很沮丧,所以那时我不会被打扰!

【问题讨论】:

  • 'commit()' 返回一个布尔状态,因此您可能需要检查以获取更多信息 - 还有为什么您依赖 'toString()' 来获取游戏统计数据而不是 stats.getInt("游戏”)?发布第一次祝酒会得到什么。
  • 我最初在 StackOverflow 上使用的帖子也希望保存变量,并且接受的答案使用 getString。 (代码有很多不同,我认为它使用的是早期版本)One I used
  • 为了清楚起见-您正在使用 SharedPreferences 实现的隐含的“toString()”来获取不属于接口的数据,因此它很可能只是 Object toString-使用适当的“getX” ' 喜欢 getInt,因为你 'putInt'。
  • 哦,我什至没有注意到!我试试看!

标签: android save saving-data


【解决方案1】:

改变这个:

CharSequence gampjla = "Games played: " + stats;

到:

CharSequence gampjla = "Games played: " + stats.getInt("gameplay",-1);

【讨论】:

    【解决方案2】:

    解决了! 这是一个愚蠢的问题。我写了“putInt”,但使用了“getString”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多