android

android 页面本地存储数据(方法和封装)

2022-01-17  本文已影响0人  KingWorld
package com.datehar.commonbase.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

/**
 * <pre>
 *     author : liangzhiyong
 *     e-mail : liangzhiyong@chicv.com
 *     time   : 2022/1/17 5:37 下午
 *     desc   :保存list数据
 *     version: 1.2.5
 * </pre>
 */
public class DataSaveUtil {

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    public DataSaveUtil(Context mContext, String preferenceName) {
        preferences = mContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    /**
     * 保存data
     * @param key
     * @param value
     */
    public  void setDataValue(String key,String value) {
        if (Tools.INSTANCE.isEmpty(value))
            return;

        Gson gson = new Gson();
        //转换成json数据,再保存
//        String strJson = gson.toJson(datalist);
        editor.clear();
        editor.putString(key, value);
        editor.commit();

    }

    /**
     * 获取data
     * @param key
     * @return
     */
    public  String getDataValue(String key) {
        String strJson = preferences.getString(key, null);
        if (null == strJson) {
            return "";
        }
//        Gson gson = new Gson();
//        datalist = gson.fromJson(strJson, new TypeToken<List<AddressDTO>>() {
//        }.getType());
        return strJson;

    }

  /**
   * 删除指定的信息
   * ***/

  public void removeUserInfo(String key){

      editor.remove(key);
      editor.commit();

  }
}


上一篇 下一篇

猜你喜欢

热点阅读