android 如何在共享首选项中保存带有模型类的Array列表?

jvlzgdj9  于 2023-09-28  发布在  Android
关注(0)|答案(4)|浏览(146)
private ArrayList<PhotoInfo> imagelist;

imagelist = new ArrayList<>();

imagelist = response.body().getPhotos();

我必须在共享首选项中保存图像
并作为数组列表从中检索

jaxagkaj

jaxagkaj1#

嘿,我做了这个简单的方法来保存和获取任何自定义模型的ArrayList到SharedPreferences
为此需要Gson依赖项:

implementation 'com.google.code.gson:gson:2.8.5'

将任何自定义列表保存到SharedPreferences

public void saveMyPhotos(ArrayList<PhotoInfo> imagelist ) {
    SharedPreferences  prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = prefs.edit();
    try {
        Gson gson = new Gson();
        String json = gson.toJson(imagelist);
        editor.putString("MyPhotos", json);
        editor.commit();     // This line is IMPORTANT !!!
    } catch (Exception e) {
        e.printStackTrace();
    }
}

SharedPreferences获取我保存的所有照片:

private ArrayList<PhotoInfo> getAllSavedMyPhotos() {
    SharedPreferences  prefs = PreferenceManager.getDefaultSharedPreferences(this);    
    Gson gson = new Gson();
    String json = prefs.getString("MyPhotos", null);
    Type type = new TypeToken<ArrayList<PhotoInfo>>() {}.getType();
    return gson.fromJson(json, type);
}
4jb9z9bj

4jb9z9bj2#

您可以使用gson库将arraylist转换为字符串,并在下面的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());
    }
}
s71maibg

s71maibg3#

首先,您需要在模型类中实现Serializable接口
接下来,在模块级build.gradle文件中添加implementation 'com.google.code.gson:gson:2.8.2'
然后,您可以通过这种方式将Arraylist保存到共享首选项/从共享首选项中检索Arraylist:

SharedPreferences preferences = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);

public List<?> getListObject(String key, Class<?> T) {
    Gson gson = new Gson();

    ArrayList<String> objStrings = getListString(key);
    ArrayList<?> objects = new ArrayList<>();

    for (String jObjString : objStrings) {
        objects.add(gson.fromJson(jObjString, (Type) T));
    }
    return objects;
}

private ArrayList<String> getListString(String key) {
    return new ArrayList<>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
}

private void putListString(String key, ArrayList<String> stringList) {
    String[] myStringList = stringList.toArray(new String[stringList.size()]);
    preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
}

public void putListObject(String key, List<Category> objArray) {
    Gson gson = new Gson();
    ArrayList<String> objStrings = new ArrayList<>();
    for (Object obj : objArray) {
        objStrings.add(gson.toJson(obj));
    }
    putListString(key, objStrings);
}
p5fdfcr1

p5fdfcr14#

1.保存数组列表

public static void saveSharedPreferencesLogList(Context context, ArrayList<MenuItemsData> collageList) {
    SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(collageList);
    prefsEditor.putString("myJson", json);
    prefsEditor.commit();
}

1.获取数组列表

public static ArrayList<MenuItemsData> loadSharedPreferencesLogList(Context context) {
   ArrayList<MenuItemsData> savedCollage = new ArrayList<MenuItemsData>();
   SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
   Gson gson = new Gson();
   String json = mPrefs.getString("myJson", "");
   if (json.isEmpty()) {
       savedCollage = new ArrayList<MenuItemsData>();
   } else {
       Type type = new TypeToken<ArrayList<MenuItemsData>>() {
       }.getType();
       savedCollage = gson.fromJson(json, type);
   }

   return savedCollage;

}

相关问题