android使用SharedPreferences保存数据

BaseAppCaching类封装了SharedPreferences的操作。这是一个基础类库,可以用于多个项目。里面将类对象转换为Json,用的是Gson的库。所以,提供了GsonUtil。但同时,为了解藕,也提供了ParseUtil类和IParseUtil协议。其中,ApplicationUtils.getApplication(),返回的是全局的application,这里替换成你自己的就行。

这是BaseAppCaching的代码:

/** * @Author Lyf * @CreateTime 2018/3/1 * @Description An BaseAppCaching class is caching data of app in SharePreference. * data will be encrypted with Base64 when it cached in SP * and decrypted with Base64 when it got from SP. **/
public class BaseAppCaching {

    private static BaseAppCaching mBaseAppCaching;

    protected static BaseAppCaching getAppCaching() {

        if (mBaseAppCaching == null) {
            synchronized (BaseAppCaching.class) {
                if (mBaseAppCaching == null) {
                    mBaseAppCaching = new BaseAppCaching();
                }
            }
        }

        return mBaseAppCaching;
    }

   /** * Uses a default key "BaseAppCaching" to save a class object in SP. */
    public <T> void saveAppCaching(T appCaching) {
        try {
            getSharedPreferences().edit().putString(this.getClass().getSimpleName(),
                    encryptCaching(ParseUtil.toJson(appCaching))).apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public <T> void saveAppCaching(String key, T appCaching) {
        try {
            getSharedPreferences().edit().putString(key,
                    encryptCaching(ParseUtil.toJson(appCaching))).apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   /** * Uses a default key "BaseAppCaching" to get a object of T from SP. */
    @Nullable
    public <T> T getAppCaching(Class<T> tClass) {

        String json = getSharedPreferences().getString(this.getClass().getSimpleName(), null);

        if (json == null) {
            return null;
        }

        return ParseUtil.parseJson(decryptCaching(json), tClass);

    }

    @Nullable
    public <T> T getAppCaching(String key, Class<T> tClass) {

        String json = getSharedPreferences().getString(key, null);

        if (json == null) {
            return null;
        }

        return ParseUtil.parseJson(decryptCaching(json), tClass);

    }

    /** * encrypt json. You can rewrite this method in subclass. */
    protected String encryptCaching(String json) throws IOException {
        return new String(Base64.encode(json.getBytes(), Base64.DEFAULT));
    }

    /** * decrypt json. You can rewrite this method in subclass. */
    protected String decryptCaching(String json) {
        return new String(Base64.decode(json, Base64.DEFAULT));
    }

    private SharedPreferences getSharedPreferences() {

        if (ApplicationUtils.getApplication() == null) {
            throw new RuntimeException("You have to initialize the mContext before invoked this method!");
        }

        return ApplicationUtils.getApplication().getSharedPreferences(ApplicationUtils.getApplication().getPackageName(), Context.MODE_PRIVATE);
    }

}

这是ParseUtil的代码:

public class ParseUtil {

    private static IParseUtil INSTANCE;

    private static IParseUtil getParseUtil() {

        if (INSTANCE == null) {
            synchronized (ParseUtil.class) {
                if (INSTANCE == null) {
                    // Instead of your parsing util if you need.
                    INSTANCE = new GsonUtil();
                }
            }
        }

        return INSTANCE;
    }

    public static <T> T parseJson(String json,  Class<T> tClass) {
        return getParseUtil().parseJson(json, tClass);
    }

    public static String toJson(Object object) {
        return getParseUtil().toJson(object);
    }

    public static <T> T parseInterfaceGenericJson(String json,  Class  tClass){
        return getParseUtil().parseInterfaceGenericJson(json,tClass);
    }

}

这是GsonUtil的代码:

public class GsonUtil implements IParseUtil {

    private static Gson gson = new Gson();

    /** * Converts a json string into a T bean. */
    public static <T> T convertJson2Bean(String json, Class<T> tClass) {
        return gson.fromJson(json, tClass);
    }

    /** * Converts an object into a string. */
    public static String convertObject2Json(Object object) {
        return gson.toJson(object);
    }

    @Override
    public <T> T parseJson(String json,  Class<T> tClass) {
        return GsonUtil.convertJson2Bean(json, tClass);
    }

    @Override
    public <T> T parseInterfaceGenericJson(String json,  Class tClass) {
        return gson.fromJson(json, (((ParameterizedType)
                (tClass.getClass().getGenericInterfaces())[0])
                .getActualTypeArguments()[0]));
    }

    @Override
    public String toJson(Object object) {
        return GsonUtil.convertObject2Json(object);
    }

}

这是接口IParseUtil的代码:

public interface IParseUtil {

    /** * Converts a json string into a T bean. */
     <T> T parseJson(String json,  Class<T> tClass);

    /** * Converts a json string into a T bean. T should be a Interface generic type. */
     <T> T parseInterfaceGenericJson(String json,  Class tClass);

    /** * Converts an object into a string. */
    String toJson(Object object);
}

这是实际使用示例:

/** * @Author Lyf * @CreateTime 2018/3/1 * @Description An AppCaching class is caching data of app in SharePreference. **/
public class AppCaching extends BaseAppCaching {

    public static void saveUserInfo(IUserInfo userInfo) {
        getAppCaching().saveAppCaching(userInfo);
    }

    public static void saveSystemConfig(ISystemConfig systemConfig) {
        getAppCaching().saveAppCaching(systemConfig);
    }

    public static IUserInfo getUserInfo() {
        return getAppCaching().getAppCaching(IUserInfo.class);
    }

    public static ISystemConfig getSystemConfig() {
        return getAppCaching().getAppCaching(ISystemConfig.class);
    }

    public static <T> void saveData(String key, T tData) {
        getAppCaching().saveAppCaching(key, tData);
    }

    public static <T> T getData(String key, Class<T> tClass) {
        return getAppCaching().getAppCaching(key, tClass);
    }

    @Override
    protected String encryptCaching(String json) throws IOException {
        return super.encryptCaching(json);
    }

    @Override
    protected String decryptCaching(String json) {
        return super.decryptCaching(json);
    }
}

附上可以跑的项目(0 warnings, 0 errors):
代码位于cache包下:
https://github.com/SuperBeagleDog/OkMVP

    原文作者:岳锋
    原文地址: https://blog.csdn.net/l_o_s/article/details/79416319
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞