`
xuanzhui
  • 浏览: 197028 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Android SharedPreferences使用

阅读更多

1. 常规操作

 

1)保存简单变量

final SharedPreferences prefs =
            activity.getSharedPreferences(CACHE_NAME, 0);

SharedPreferences.Editor spEditor = prefs.edit();
spEditor.putString(CACHED_STR_CONSTANT_NAME, cachedStr);

spEditor.apply();

 

2)读取简单变量

String cacheStr = activity.getSharedPreferences(CACHE_NAME, 0)
            .getString(CACHED_STR_CONSTANT_NAME, null);

 

3)删除特定变量

final SharedPreferences prefs =
        activity.getSharedPreferences(CACHE_NAME, 0);
SharedPreferences.Editor spEditor = prefs.edit();

spEditor.remove(CACHED_STR_CONSTANT_NAME);

spEditor.apply();

 

4)清空所有变量

final SharedPreferences prefs =
        activity.getSharedPreferences(CACHE_NAME, 0);
SharedPreferences.Editor spEditor = prefs.edit();
spEditor.clear();
spEditor.apply();

 

2. 复杂类型

       可以考虑SQLite,但是如果数据量并不是很大可以考虑先转成json字符串,再存储;读取的时候再将该json串转化为对象。

 

比如要保留N个商品的信息

1)首先创建GoodsItem类:

public class GoodsItem {
    String goodsName;
    Float goodsPrice;

    //...
}

 

2)然后创建用于json解析的class,包含所有数据的字段:

public class CachedGoodsItems {
    List<GoodsItem> goodsItems;
    //...
}

 

3)存储(此处使用Gson将对象转换为json串,cachedGoodsItems为CachedGoodsItems 类型)

Gson gson = new Gson();
String cachedStr = gson.toJson(cachedGoodsItems);

final SharedPreferences prefs =
    	activity.getSharedPreferences(CACHE_NAME, 0);
SharedPreferences.Editor spEditor = prefs.edit();
spEditor.putString(CACHED_STR_CONSTANT_NAME, cachedStr);

spEditor.apply();

 

4)读取(此处使用Gson解析,cachedGoodsItems为CachedGoodsItems 类型)

String cacheStr = activity.getSharedPreferences(CACHE_NAME, 0)
                .getString(CACHED_STR_CONSTANT_NAME, null);

if (cacheStr != null) {
    Gson gson = new Gson();
    cachedGoodsItems = gson.fromJson(cacheStr, new TypeToken<CachedGoodsItems>() {
            }.getType());
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics