android SharedPreferences保存应用数据
16lz
2021-01-26
之前就在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();}
其中奥妙还未得解,望高人指点。
已经解决,见下面回复。
更多相关文章
- 一句话锁定MySQL数据占用元凶
- Intent的传递
- Android(安卓)数据存储——shared preferences
- Android学习笔记(十九)分享简单数据
- Bitmap和libyuv在JNI中的字节序
- Android文本EditorText相关问题
- Android短信数据库字段描述
- Android(安卓)ANT工程创建
- [置顶] Android(安卓)Camera系统