SharedPreferences保持对象数据
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;
    }



    //


}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QQ1375235976/article/details/51545556
文章标签: android java 数据
个人分类: Android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

SharedPreferences保持对象数据

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭