You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:游戏统计数据存储——SharedPreferences使用失败问题排查

关于使用SharedPreferences保存游戏统计数据的解决方案

嘿,你选SharedPreferences来存这类轻量的游戏统计数据完全没问题!从你贴的代码片段来看,确实有几个小细节没处理好,导致功能没跑通,我帮你梳理并修正一下:

先说说你代码里的问题

  • 变量名拼写错误:你写的gampjla和gampjl明显是手滑打错了,这类拼写错误会直接导致编译或运行出错,建议用gamesPlayedText这类有意义的变量名。
  • 直接拼接SharedPreferences对象:"Games played: " + stats这里犯了个基础错误——stats是SharedPreferences的实例对象,不是你要的统计数值,得调用getInt()(或对应类型的方法)才能取出存在里面的具体数据。
  • 缺少数据写入逻辑:如果只做读取操作,那永远只会拿到初始默认值,玩游戏后的统计数据根本没法更新保存。

给你完整的正确实现示例

1. 写入统计数据(比如每次游戏结束后调用)

// 获取全局可用的SharedPreferences实例,指定一个自定义名称"GameStats"
SharedPreferences stats = getSharedPreferences("GameStats", MODE_PRIVATE);
SharedPreferences.Editor editor = stats.edit();

// 取出当前已游玩次数,默认值设为0(第一次运行时用)
int currentGamesPlayed = stats.getInt("games_played", 0);
// 游玩次数+1
editor.putInt("games_played", currentGamesPlayed + 1);

// 同理处理获胜次数
int currentWins = stats.getInt("wins", 0);
// 假设这里通过判断确定玩家获胜了,就把获胜次数+1
if (playerWon) {
    editor.putInt("wins", currentWins + 1);
}

// 提交修改:apply()是异步提交(推荐),commit()是同步提交
editor.apply();

2. 读取并显示统计数据

Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;

SharedPreferences stats = getSharedPreferences("GameStats", MODE_PRIVATE);
// 取出游玩次数和获胜次数,默认值都是0
int gamesPlayed = stats.getInt("games_played", 0);
int wins = stats.getInt("wins", 0);

// 拼接成要显示的文本
CharSequence statsText = "Games played: " + gamesPlayed + "\nWins: " + wins;
Toast toast = Toast.makeText(context, statsText, duration);
toast.show();

额外的小提示

  • 选择合适的SharedPreferences实例:getPreferences(MODE_PRIVATE)是当前Activity专属的存储,如果你的游戏有多页面需要共享统计数据,用getSharedPreferences("自定义名称", MODE_PRIVATE)更灵活。
  • 默认值的作用:getInt()的第二个参数是默认值,第一次运行App还没存过数据时,会用这个值初始化,避免出现异常。
  • 线程安全:SharedPreferences的读取和编辑操作尽量在主线程执行,避免线程安全问题。

内容的提问来源于stack exchange,提问作者Ollie R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:25:30