之前就在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 context
Constants.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();
}
其中奥妙还未得解,望高人指点。
已经解决,见下面回复。