【问题标题】:How to save Array list with model class in shared preference?如何在共享首选项中保存带有模型类的数组列表?
【发布时间】:2019-09-27 06:03:27
【问题描述】:
private ArrayList<PhotoInfo> imagelist;


imagelist = new ArrayList<>();

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

我必须在共享偏好中保存图片

并从 Arraylist 中检索

【问题讨论】:

标签: android sharedpreferences


【解决方案1】:

嘿,我做了这个简单的方法来保存和获取任何自定义模型的 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);
}

【讨论】:

  • @Rajesh 很高兴这对你有帮助.. :)
【解决方案2】:

您可以使用 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());
    }
}

【讨论】:

    【解决方案3】:

    首先,你需要在你的模型类中实现Serializable接口

    接下来,在你的模块级build.gradle文件中添加implementation 'com.google.code.gson:gson:2.8.2'

    然后,您可以通过这种方式将您的 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 1970-01-01
      • 2021-11-05
      • 2017-04-26
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2023-03-07
      相关资源
      最近更新 更多