使用sharepreference保存获取对象

1.获取对象

2.给对象赋值

3.创建SPUtil工具类

如下

public class SpUtils {
    //此处设置默认文件名
    private static final String DEFAULT_SP_NAME = "default_sp";

    public static  T getObject(Context context, Class clazz) {
        String key = getKey(clazz);
        String json = getString(context, key, null);
        if (TextUtils.isEmpty(json)) {
            return null;
        }
        try {
            Gson gson = new Gson();
            return gson.fromJson(json, clazz);
        } catch (Exception e) {
            return null;
        }
    }

    public static void putObject(Context context, Object object) {
        String key = getKey(object.getClass());
        Gson gson = new Gson();
        String json = gson.toJson(object);
        putString(context, key, json);
    }

    public static void removeObject(Context context, Class clazz) {
        remove(context, getKey(clazz));
    }

    public static String getKey(Class clazz) {
        return clazz.getName();
    }

    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(DEFAULT_SP_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.remove(key);
        edit.commit();
    }

    public static void putString(Context context, String key, String value) {
        SharedPreferences sp = context.getSharedPreferences(DEFAULT_SP_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, value);
        edit.commit();
    }

    public static String getString(Context context, String key, String defValue) {
        SharedPreferences sp = context.getSharedPreferences(DEFAULT_SP_NAME, Context.MODE_PRIVATE);
        return sp.getString(key, defValue);
    }

}

4.传值

 Bean bean=new Bean(1,"ash");

SpUtils.putObject(this,bean);

5.拿值

try {
    Class aa = Class.forName("com.example.tent.Bean");
   Bean bb= (Bean) SpUtils.getObject(this,aa);
    int dd=bb.id;
 
}  catch (ClassNotFoundException e) {
    e.printStackTrace();
}

 

备注:moudle里引入依赖  implementation 'com.google.code.gson:gson:2.6.2'

 

你可能感兴趣的:(使用sharepreference保存获取对象)