把数据写入缓存
/**
* 保存兑换专区商品列表
* @param version
*/
public static void saveExchangeProducts(Context context, ExchangeGroupProductListResponseVo exchangeGroupProductListResponseVo) {
try {
String jsonStr = new Gson().toJson(exchangeGroupProductListResponseVo);
SharedPreferences sharedPreferences = context.getSharedPreferences(WalletThirdHelper.EXCHANGE_PRODUCT, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(WalletThirdHelper.EXCHANGE_PRODUCT, jsonStr);
editor.apply();
}catch (Exception e){
e.printStackTrace();
}
}
从缓存中获取数据
/**
* 获取缓存的兑换专区商品列表
* @param version
*/
private static ExchangeGroupProductListResponseVo getExchangeProducts(Context context) {
try {
SharedPreferences sharedPreferences = context.getSharedPreferences(WalletThirdHelper.EXCHANGE_PRODUCT, 0);
String jsonStr = sharedPreferences.getString(WalletThirdHelper.EXCHANGE_PRODUCT, "");
if (TextUtils.isEmpty(jsonStr)) return null;
return new Gson().fromJson(jsonStr, ExchangeGroupProductListResponseVo.class);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
注意⚠️
开发过程中发现明明存进去了,但取不出数据。就把存数据按照下面处理:editor的获取和数据的存储分开书写:
SharedPreferences sharedPreferences = context.getSharedPreferences(WalletThirdHelper.EXCHANGE_PRODUCT, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(WalletThirdHelper.EXCHANGE_PRODUCT, jsonStr);
editor.apply();
网友评论