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()); }
相关推荐
SXIAOYI 2020-09-16
xiaonuoyal 2020-06-17
SXIAOYI 2020-06-11
yinbaoshiguang 2020-06-09
Chydar 2020-06-02
nalanrumeng 2020-06-01
xiaonuoyal 2020-06-01
nalanrumeng 2020-05-19
ITprivate 2020-04-15
xiaonuoyal 2020-04-14
ITprivate 2020-03-26
ITprivate 2020-02-12
nalanrumeng 2020-01-13
xiaonuoyal 2019-12-07
xiaonuoyal 2019-11-18
TOmyhonour 2019-11-16