2017-07-22 31 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

相關問題