ArrayList<Class> sharedpreferences

huangapple go评论79阅读模式
英文:

ArrayList<Class> sharedpreferences

问题

有没有办法将ArrayList<Class>保存到sharedpreferences?谢谢

ArrayList<Class> activityList = new ArrayList<>();
activityList.add(Level1Activity.class);
activityList.add(Level2Activity.class);
activityList.add(Level3Activity.class);
activityList.add(Level4Activity.class);
activityList.add(Level5Activity.class);

英文:

Is it any way to save ArrayList<Class> to sharedpreferences? Thank you

ArrayList&lt;Class&gt; activityList = new ArrayList&lt;&gt;();
activityList.add(Level1Activity.class);
activityList.add(Level2Activity.class);
activityList.add(Level3Activity.class);
activityList.add(Level4Activity.class);
activityList.add(Level5Activity.class);

答案1

得分: 1

我已经在你的另一个问题中回答了这个问题,但以防万一,我会在这里重新写一遍并且更详细地解释。

你可以使用 Gson 将你的列表转换成一个 Json 字符串,这样你就可以将它保存在 SharedPreferences 中。

你需要在你的应用 gradle 依赖中添加 implementation 'com.google.code.gson:gson:2.8.6',以便能够使用 Gson

但是,当你使用 Class 类时,不能简单地使用 Gson 解析列表为 Json 或者反过来。为了做到这一点,你需要为它创建自己的 序列化器反序列化器。否则你会遇到这个异常:

java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: com.etc.etc.Level1Activity. Forgot to register a type adapter?

<br>

所以让我们创建一个实现了 JsonSerializerJsonDeserializer 的自定义适配器。不要忘记在尖括号中放入我们正在处理的类型,也就是 Class

ClassAdapter 类

public class ClassAdapter implements JsonSerializer&lt;Class&gt;, JsonDeserializer&lt;Class&gt; {

    @Override
    public JsonElement serialize(Class src, Type typeOfSrc, JsonSerializationContext context) {
        // 获取我们类的名字
        return new JsonPrimitive(src.getName());
    }

    @Override
    public Class deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            // 获取类
            return Class.forName(json.getAsString());
        } catch (ClassNotFoundException e) {
            // 如果找不到类或类不存在,在这里处理错误...
            e.printStackTrace();
        }
        return null;
    }

}

将我们的列表转换成 Json 字符串 并保存到 SharedPreferences 中:

// 创建新的 GsonBuilder 并为 Class 对象注册适配器
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());

// 初始化我们的级别列表(即类)
List&lt;Class&gt; classes = new ArrayList&lt;&gt;();
classes.add(Level1Activity.class);
classes.add(Level2Activity.class);
classes.add(Level3Activity.class);
classes.add(Level4Activity.class);
classes.add(Level5Activity.class);

// 从 GsonBuilder 创建 Gson 并将列表转换为 json
Gson gson = gsonBuilder.create();
String json = gson.toJson(classes);

// 将 json 保存到 SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
sharedPreferences.edit().putString("levels", json).apply();

然后要检索回列表:

// 从 SharedPreferences 中检索 json
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
String json = sharedPreferences.getString("levels", null);

// 如果 json 不存在的话在这里处理
if (json == null) {
    // ...
}

// 创建新的 GsonBuilder 并为 Class 对象注册适配器
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());

// 从 GsonBuilder 创建 Gson 并指定列表的类型
Gson gson = gsonBuilder.create();
Type type = new TypeToken<ArrayList<Class>>(){}.getType();

// 将 json 转换为列表
List<Class> classes = gson.fromJson(json, type);

希望这有所帮助,愉快编码!

英文:

I already answered this to your other question but just in case, I'll re-write it here and explain it more a bit.

You can use Gson to convert your list into a Json String so that you can save it in SharedPreferences.

You will need to add implementation &#39;com.google.code.gson:gson:2.8.6&#39; inside your app gradle dependencies to be able to use Gson.

But, you cannot simply parse the list using Gson to Json or viceversa when you use the Class class. In order to do so, you will need to create your own serializer and deserializer for it. Or you'll face this exception:

java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: com.etc.etc.Level1Activity. Forgot to register a type adapter?

<br>

So let's create a custom adapter that implements JsonSerializer and JsonDeserializer. Don't forget to put inside the angle brackets the type we're working with, which is Class.

ClassAdapter class

public class ClassAdapter implements JsonSerializer&lt;Class&gt;, JsonDeserializer&lt;Class&gt; {

    @Override
    public JsonElement serialize(Class src, Type typeOfSrc, JsonSerializationContext context) {
        // Get our class &#39;src&#39; name
        return new JsonPrimitive(src.getName());
    }

    @Override
    public Class deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            // Get class
            return Class.forName(json.getAsString());
        } catch (ClassNotFoundException e) {
            // If class could not be found or did not exists, handle error here...
            e.printStackTrace();
        }
        return null;
    }

}

To convert our list to Json String and save it inside SharedPreferences:

// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());

// Initialize our list of levels (ie. classes)
List&lt;Class&gt; classes = new ArrayList&lt;&gt;();
classes.add(Level1Activity.class);
classes.add(Level2Activity.class);
classes.add(Level3Activity.class);
classes.add(Level4Activity.class);
classes.add(Level5Activity.class);

// Create Gson from GsonBuilder and convert list to json
Gson gson = gsonBuilder.create();
String json = gson.toJson(classes);

// Save json to SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences(&quot;app_name&quot;, MODE_PRIVATE);
sharedPreferences.edit().putString(&quot;levels&quot;, json).apply();

And to retrieve the list back:

// Retrieve json from SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences(&quot;app_name&quot;, MODE_PRIVATE);
String json = sharedPreferences.getString(&quot;levels&quot;, null);

// Handle here if json doesn&#39;t exist yet
if (json == null) {
    // ...
}

// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());

// Create Gson from GsonBuilder and specify type of list
Gson gson = gsonBuilder.create();
Type type = new TypeToken&lt;ArrayList&lt;Class&gt;&gt;(){}.getType();

// Convert json to list
List&lt;Class&gt; classes = gson.fromJson(json, type);

Hope this helps, happy coding!

huangapple
  • 本文由 发表于 2020年5月5日 01:46:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定