2017-09-04 47 views
1

我使用GSON的Android:无法用无参数

救了我的自定义模型的ArrayList到共享偏好来调用私有android.net.Uri()存储代码:

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

回答

2

Uri类的构造函数是私有的,它是一个抽象类。 Gson尝试使用Reflection API为Uri类创建一个新对象(我们不能为抽象类创建对象)。所以简单的解决方案是将uriPath更改为String而不是Uri

private String uriPath;