我正在使用 Gson 将自定义模型的数组列表保存到共享首选项中
存储代码:
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
Model
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 https://developer.android.com/reference/android/net/Uri.html类构造函数是私有的,它是一个抽象类。 Gson 尝试创建一个新对象Uri
使用Reflection API创建类(我们不能为抽象类创建对象)。所以简单的解决方案就是改变uriPath
into String
代替Uri
.
private String uriPath;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)