【问题标题】:Unable to save SharedPreferences using Gson on ArrayList of custom objects无法在自定义对象的 ArrayList 上使用 Gson 保存 SharedPreferences
【发布时间】:2017-12-28 05:54:54
【问题描述】:

我在这里尝试最佳答案中的解决方案:Android ArrayList of custom objects - Save to SharedPreferences - Serializable?

我正在尝试将自定义对象的 ArrayList 保存到 SharedPreferences。

SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(baseApplication);
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(masterPinList);
prefsEditor.putString("masterPinList", json);
prefsEditor.apply();

masterPinList 是自定义对象的 ArrayList (Pin)。

错误是:

java.lang.SecurityException: Can not make a java.lang.reflect.Method constructor accessible

错误出现在这一行:

String json = gson.toJson(masterPinList);

怎么了?

【问题讨论】:

  • 显示Pin的代码
  • Pin 引用了应用程序和其他自定义对象。根据下面的答案,并在使用另一个自定义对象进行测试后,我发现在不引用应用程序中的上下文或其他自定义对象的情况下制作 Pin 对象会更容易。

标签: java android arraylist gson sharedpreferences


【解决方案1】:

您可以尝试向该类添加一个空的构造函数,因为这将用于设置值。

public className() {

}

【讨论】:

    【解决方案2】:

    你的对象是可序列化的吗?这可能是问题所在。这是一个示例类

    public class PlanDateObject {
    
    @SerializedName("DateList")
    private List<String> dateList;
    @SerializedName("PlanList")
    private List<Plan> planList;
    
    public List<String> getDateList() {
        return dateList;
    }
    
    public void setDateList(List<String> dateList) {
        this.dateList = dateList;
    }
    
    public List<Plan> getPlanList() {
        return planList;
    }
    
    public void setPlanList(List<Plan> planList) {
        this.planList = planList;
    }
    

    }

    【讨论】:

    • 此对象引用的所有其他自定义对象是否也需要可序列化,因为仅使 Pin 可序列化不起作用?
    • 是的。我用这个类测试了你的代码,它工作了
    猜你喜欢
    • 2018-09-16
    • 2018-07-31
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    相关资源
    最近更新 更多