static int getIntPref(Context context, String name, int def) {
SharedPreferences prefs = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
return prefs.getInt(name, def);
}
static void setIntPref(Context context, String name, int value) {
SharedPreferences prefs = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putInt(name, value);
ed.commit();
SharedPreferences prefs = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
return prefs.getInt(name, def);
}
static void setIntPref(Context context, String name, int value) {
SharedPreferences prefs = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putInt(name, value);
ed.commit();
}
这两个函数, 我已经使用过了, 我们从里面可以看到
它的使用方法, 但是我居然花了两个小时, 才让它可以
使用, 那到底我忽略了什么了呢, 请注意上面红色部份:
ed.commit();, 晕死了, 出了这个问题, 我真没想到,
所以分享大家, 希望大家不要和我范同样的错误
本文详细解析了在Android开发中使用SharedPreferences进行数据存储的方法,特别强调了commit方法的作用及其忽略可能导致的问题。通过实例说明,帮助开发者避免常见错误,确保数据持久化的正确实现。

1813

被折叠的 条评论
为什么被折叠?



