android SharedPreferences保存应用数据

来源:互联网 发布:windows系统升级 编辑:程序博客网 时间:2024/05/23 19:18

之前就在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();}

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

已经解决,见下面回复。



原创粉丝点击