英文:
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<Class> activityList = new ArrayList<>();
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>
所以让我们创建一个实现了 JsonSerializer
和 JsonDeserializer
的自定义适配器。不要忘记在尖括号中放入我们正在处理的类型,也就是 Class
。
ClassAdapter 类
public class ClassAdapter implements JsonSerializer<Class>, JsonDeserializer<Class> {
@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<Class> classes = new ArrayList<>();
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 'com.google.code.gson:gson:2.8.6'
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<Class>, JsonDeserializer<Class> {
@Override
public JsonElement serialize(Class src, Type typeOfSrc, JsonSerializationContext context) {
// Get our class 'src' 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<Class> classes = new ArrayList<>();
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("app_name", MODE_PRIVATE);
sharedPreferences.edit().putString("levels", json).apply();
And to retrieve the list back:
// Retrieve json from SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
String json = sharedPreferences.getString("levels", null);
// Handle here if json doesn'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<ArrayList<Class>>(){}.getType();
// Convert json to list
List<Class> classes = gson.fromJson(json, type);
Hope this helps, happy coding!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论