之前就在Android里使用SharedPreferences保存一些数据了,简单的到网上搜了下就开始使用了,昨天再次使用居然无法保存,后来找到了问题所在,记录在此。

我是在做游戏开发,使用Constants保存游戏中的一些常量,如下

public class Constants {public static Engine mEngine;public static Context mContext;public static final float CAMERA_WIDTH = 320;public static final float CAMERA_HEIGHT = 480;}

我的程序入口类继承自SimpleBaseGameActivity

并在onCreateResources()方法中给上面Constants类中的mContext赋了值

// application contextConstants.mContext = this;

接下来要说到关键地方了,我一开始保存和读取数据的实现类如下:

public class Settings {private static String PREFS_NAME = "cn.wey.android.huarong";public static boolean soundEnabled = true;/** * save game settings */public static void save() {SharedPreferences sp = Constants.mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);sp.edit().putBoolean("soundEnable", soundEnabled);sp.edit().commit();}/** * load game settings */public static void load() {SharedPreferences sp = Constants.mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);soundEnabled = sp.getBoolean("soundEnable", true);}}
结果导致数据无法保存,后经我测试才发现保存数据的函数应该这样写:

       /** * save game settings */public static void save() {SharedPreferences sp = Constants.mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);SharedPreferences.Editor edit = sp.edit();edit.putBoolean("soundEnable", soundEnabled);edit.commit();}

其中奥妙还未得解,望高人指点。

已经解决,见下面回复。



更多相关文章

  1. 一句话锁定MySQL数据占用元凶
  2. Intent的传递
  3. Android(安卓)数据存储——shared preferences
  4. Android学习笔记(十九)分享简单数据
  5. Bitmap和libyuv在JNI中的字节序
  6. Android文本EditorText相关问题
  7. Android短信数据库字段描述
  8. Android(安卓)ANT工程创建
  9. [置顶] Android(安卓)Camera系统

随机推荐

  1. 分布式消息队列 RocketMQ 源码分析 ——
  2. 免费且支持远程连接的MySql空间
  3. 专访|腾讯UI工程师@张鑫旭
  4. Android(安卓)SQLite详解
  5. git命令备忘系列(一):基础命令
  6. 专访|前端布道师@张克军
  7. http协议请求方法都有哪些?网络安全学习提
  8. 【第554期】Webpack 一探究竟
  9. Android(安卓)设置dialog背景全透明无边
  10. 单页应用 & 多页应用的区别