美文网首页
55. 利用SharedPreferences做缓存

55. 利用SharedPreferences做缓存

作者: TensorFlow开发者 | 来源:发表于2019-11-21 14:25 被阅读0次

    把数据写入缓存

        /**
         * 保存兑换专区商品列表
         * @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();
    

    相关文章

      网友评论

          本文标题:55. 利用SharedPreferences做缓存

          本文链接:https://www.haomeiwen.com/subject/qfctwctx.html