在 SharedPreferences 中存储对象集合 [英] Store a collection of objects in SharedPreferences

查看:40
本文介绍了在 SharedPreferences 中存储对象集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个实用程序类,用于在 SharedPreferences 中存储数据.到目前为止,我已经能够创建一个通用函数来存储和检索 String、int 和 boolean.有没有一种通用的方法来存储和检索对象集合?

I am working on a developing a utility class for storing data in SharedPreferences. Till now, I was able to make a generic function to store and retrieve String, int and boolean. Is there a generic way to store and retrieve a collection of objects?

推荐答案

没有直接的方式,只有两种间接的方式:

There is no direct way but two indirect ways:

1.使用 GSON.

public static boolean saveObjectToPrefs(String prefKey, Object object, Context context) {
    SharedPreferences.Editor editor = getSharedPreferences(context).edit();
    try {
        Gson gson = new Gson();
        String json = gson.toJson(object);
        editor.putString(prefKey, json);
        editor.apply();
        return true;
    } catch (Exception e) {
         e.printStackTrace();
         return false;
    }
}

这里的泛型应该实现Serializable接口.

The generic here should implement Serializable interface.

要检索对象,请创建如下方法:

To retrieve object create a method like this:

public static <T> T getObjectFromPrefs(String prefKey, Class<T> type, Context context) {
    String json = getSharedPreferences(context).getString(prefKey, null);
    if (json != null) {
        try {
            Gson gson = new Gson();
            T result = gson.fromJson(json, type);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

你可以像集合一样调用这个方法:

and you can call this method like for collections:

PrefUtils.getObjectFromPrefsByType(PREF_KEY_USERS, new TypeToken<ArrayList<User>>() {
    }.getType(), context);

对于普通对象,您可以:

for normal objects you can do:

PrefUtils.getObjectFromPrefsByType(PREF_KEY_USER, User.class, context);

2.编写自定义序列化器和反序列化器

我通常更喜欢这种方法,因为我不必为它包含一个库.

I usually prefer this method as I don't have to include a library for it.

这是自定义序列化器/解串器实现:

Here is the custom serializer/deserializer implemetation:

public class ObjectSerializer {


public static String serialize(Serializable obj){
    if (obj == null) return "";
    try {
        ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
        ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
        objStream.writeObject(obj);
        objStream.close();
        return encodeBytes(serialObj.toByteArray());

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

public static Object deserialize(String str)  {
    if (str == null || str.length() == 0) return null;
    try {
        ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
        ObjectInputStream objStream = new ObjectInputStream(serialObj);
        return objStream.readObject();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

public static String encodeBytes(byte[] bytes) {
    StringBuilder strBuf = new StringBuilder();
    for (Byte b: bytes) {
        strBuf.append((char) (((b >> 4) & 0xF) + ((int) 'a')));
        strBuf.append((char) (((b) & 0xF) + ((int) 'a')));
    }
    return strBuf.toString();
}

public static byte[] decodeBytes(String str) {
    byte[] bytes = new byte[str.length() / 2];
    for (int i = 0; i < str.length(); i+=2) {
        char c = str.charAt(i);
        bytes[i/2] = (byte) ((c - 'a') << 4);
        c = str.charAt(i+1);
        bytes[i/2] += (c - 'a');
    }
    return bytes;
    }
}

现在,在 PrefUtils.java 中,您可以使用如下方法:

Now, inside PrefUtils.java you can have method like:

public static void saveUser(Context context, User user) {
    getSharedPreferences(context)
                        .edit()
                        .putString(PREF_KEY_USER, ObjectSerializer.serialize(user))
                        .apply();
}

要检索对象,您可以使用以下方法:

To retrieve the object you can use following method:

public static User getUser(Context context) {
    String serializedUser = getSharedPreferences(context).getString(PREF_KEY_USER, "");
    return ((User) ObjectSerializer.deserialize(serializedUser));
}

再一次,用户类必须是可序列化的.另外,不要忘记显式转换,因为 ObjectSerializer.deserialize(String str) 方法返回 Object 类型的对象,而不是您序列化的类.另外,请注意空值.

Again User class has to be Serializable. Also, don't forgot explicit casting as ObjectSerializer.deserialize(String str) method returns an object of type Object and not the class you serialized. Also, take care of null values.

这篇关于在 SharedPreferences 中存储对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆