关闭

SharedPreferences保持对象数据

标签: androidjava数据
291人阅读 评论(0) 收藏 举报
分类:
public class SharedPrefUtils {

    //SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下:

    private SharedPrefUtils() { }


    private static SharedPrefUtils sharedPrefUtils;
    public static SharedPrefUtils getInstance() {
        if (sharedPrefUtils == null) {
            synchronized (SharedPrefUtils.class) {
                if (sharedPrefUtils == null) {
                    sharedPrefUtils = new SharedPrefUtils();
                }
            }
        }
        return sharedPrefUtils;
    }

    private static Gson gson;
    public static Gson getInstanceGson() {
        if (gson == null) {
            synchronized (SharedPrefUtils.class) {
                if (gson == null) {
                    gson = new Gson();
                }
            }
        }
        return gson;
    }


    private static final String comm_name="comm_name";

    private static SharedPreferences init(String name){
        getInstance();
        return MyApp.getApp().getSharedPreferences(name, Context.MODE_PRIVATE);
    }


    //
    public static void putKV(String key, String vaule){
        SharedPreferences sp = init(comm_name);
        Editor editor = sp.edit();
        editor.putString(key, vaule);
        editor.commit();
    }

    public static String getKV(String key){
        SharedPreferences sp = init(comm_name);
        return sp.getString(key, "");
    }


    //
    public static void putObject(String key, Object vaule){
        SharedPreferences sp = init(comm_name);
        Editor editor = sp.edit();
        String objJson=getInstanceGson().toJson(vaule);
        editor.putString(key, objJson);
        editor.commit();
    }

    public static Object getObject(String key, Class<?> vaule){
        SharedPreferences sp = init(comm_name);
        Object t = getInstanceGson().fromJson(sp.getString(key, ""), vaule);
        return t;
    }
    public static Object getObject(Class<?> vaule){
        SharedPreferences sp = init(comm_name);
        Object t = getInstanceGson().fromJson(sp.getString(vaule.getName(), ""), vaule);
        return t;
    }



    //


}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10591次
    • 积分:239
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:0篇
    • 译文:2篇
    • 评论:1条
    文章分类
    文章存档