Sye*_*idi 3 java android gson sharedpreferences
我使用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();
}
Run Code Online (Sandbox Code Playgroud)
检索
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
}
Run Code Online (Sandbox Code Playgroud)
但是我得到的错误行:无法实例化类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;
}
}
Run Code Online (Sandbox Code Playgroud)
Uri类构造函数是私有的,它是一个抽象类.Gson尝试Uri使用Reflection API 为类创建一个新对象(我们不能为抽象类创建一个对象).这么简单的解决方案就是uriPath改成String而不是Uri.
private String uriPath;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2662 次 |
| 最近记录: |