[英]Android: Failed to invoke private android.net.Uri() with no args
我使用Gson將自定義模型的arraylist保存到共享首選項中
存儲代碼:
ArrayList<DownloadProgressDataModel> arrayList = getArrayListFromPref(downloadProgressDataModel);
SharedPreferences.Editor prefsEditor = getSharedPreferences("APPLICATION_PREF", MODE_PRIVATE).edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
prefsEditor.putString("DownloadManagerList", json);
prefsEditor.apply();
}
檢索
ArrayList<DownloadProgressDataModel> arrayList;
Gson gson = new Gson();
SharedPreferences mPrefs = getSharedPreferences("APPLICATION_PREF", MODE_PRIVATE);
String json = mPrefs.getString("DownloadManagerList", "");
if (json.isEmpty()) {
arrayList = new ArrayList<DownloadProgressDataModel>();
} else {
Type uriPath = new TypeToken<ArrayList<DownloadProgressDataModel>>() {
}.getType();
arrayList = gson.fromJson(json, uriPath); <------ Error line
}
但是我得到的錯誤行: 無法實例化類android.net.Uri
模型
public class DownloadProgressDataModel {
private Uri uriPath;
private long referenceId;
public Uri getUriPath() {
return uriPath;
}
public void setUriPath(Uri uriPath) {
this.uriPath = uriPath;
}
public long getReferenceId() {
return referenceId;
}
public void setReferenceId(long referenceId) {
this.referenceId = referenceId;
}
}
Uri類構造函數是私有的,它是一個抽象類。 Gson嘗試使用Reflection API為Uri
類創建一個新對象(我們不能為抽象類創建一個對象)。 如此簡單的解決方案是將uriPath
更改為String
而不是Uri
。
private String uriPath;
meh,只是從序列化/反序列化過程中排除有問題的實例變量 。 Gson:如何在沒有注釋的情況下從序列化中排除特定字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.