gpt4 book ai didi

java - 使用对象类型将数组列表存储在共享首选项中

转载 作者:行者123 更新时间:2023-12-01 22:30:10 26 4
gpt4 key购买 nike

我有一个 list_beneficiaries 数组列表(类型:受益人)。在该数组列表中,我有类似受益人对象类型的元素。像这样的事情,

list_beneficiaries.add(new Beneficiary(Integer.parseInt(obj2.getString("id")),
obj2.getString("ben_firstname"), obj2.getString("ben_lastname"));

我想在共享首选项中添加此数组列表并检索它。我怎样才能做到这一点?我尝试使用这个 stackoverflow 答案:Save ArrayList to SharedPreferences

但是,我没有得到我想要的结果。因为我有一个数组类型的对象。

最佳答案

我真的很喜欢Gson。它很容易使用:

  1. Download the jar并保存到app/libs/

  2. 更新 gradle 依赖项 (build.gradle):

    dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.code.gson:gson:2.3'
    }
  3. 更新您的代码:

    ArrayList<MyClass> array = new ArrayList<>();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = prefs.edit();

    // Put
    Gson gson = new Gson();
    String json = gson.toJson(array);
    editor.putString("preference_key", json);
    editor.commit(); //every change in editor object is commited.
    // Get
    json = prefs.getString("preference_key", null);
    java.lang.reflect.Type type = new TypeToken<ArrayList<MyClass>>(){}.getType();
    array = gson.fromJson(json, type);

关于java - 使用对象类型将数组列表存储在共享首选项中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com