您可以使用 gson 库将您的数组列表转换为字符串,并在下面的 SharedPreferences 代码中存储和获取
在 gradle 依赖中添加这个
api 'com.google.code.gson:gson:2.8.5'
将您的列表转换为字符串并存储在 SharedPreferences 中
public static boolean writePhotoInfoJSON(List<PhotoInfo> sb, Context context)
{
try {
SharedPreferences mSettings =
context.getSharedPreferences("yourSharedPreNme", Context.MODE_PRIVATE);
String writeValue = new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriSerializer())
.create()
.toJson(sb, new TypeToken<ArrayList<PhotoInfo>>()
{}.getType());
SharedPreferences.Editor mEditor = mSettings.edit();
mEditor.putString("shringName", writeValue);
mEditor.apply();
return true;
} catch(Exception e)
{
return false;
}
}
获取您的自定义数组列表
public static ArrayList<PhotoInfo> readPhotoInfoJSON(Context context)
{
if(context==null){
return new ArrayList<>();
}
try{
SharedPreferences mSettings =
context.getSharedPreferences("yourSharedPreNme", Context.MODE_PRIVATE);
String loadValue = mSettings.getString("shringName", "");
Type listType = new TypeToken<ArrayList<PhotoInfo>>(){}.getType();
return new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriDeserializer())
.create()
.fromJson(loadValue, listType);
}catch (Exception e){
e.printStackTrace();
}
return new ArrayList<>();
}
public static class UriDeserializer implements JsonDeserializer<Uri> {
@Override
public Uri deserialize(final JsonElement src, final Type srcType,
final JsonDeserializationContext context) throws
JsonParseException {
return Uri.parse(src.toString().replace("\"", ""));
}
}
public static class UriSerializer implements JsonSerializer<Uri> {
public JsonElement serialize(Uri src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}