2017-07-22 28 views
0

我想在这里顶端应答解决方案:Android ArrayList of custom objects - Save to SharedPreferences - Serializable?无法保存使用GSON SharedPreferences定制的ArrayList的对象

我想保存到SharedPreferences自定义对象的ArrayList。

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)。

的错误是:

String json = gson.toJson(masterPinList); 

什么是错的:在此行中出现

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

的错误?

+0

显示为'Pin' – weston

+0

PIN码的应用和其他自定义对象的引用代码。基于下面的答案,并且在用另一个自定义对象进行测试后,我发现在应用中没有对上下文或其他自定义对象的引用的情况下制作Pin对象会更容易。 – user1755043

回答

0

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

public className() { 

} 
0

对象是否可序列化?这可能是问题所在。下面是一个例子类

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; 
} 

}

+0

此对象引用的每个其他自定义对象是否也需要可序列化,因为只是使可串行化的引脚不起作用? – user1755043

+0

是的。我用这个类测试了你的代码,它工作 – FnR

相关问题