2017-09-04 3 views
1

Je sauve mon arraylist de modèle personnalisé en utilisant la préférence partagée GsonAndroid: Impossible d'invoquer android.net.Uri() privée sans args

Code de stockage:

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

Récupération

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 
     } 

Mais sur la ligne d'erreur que je reçois: ne peut pas instancier classe android.net.Uri

Modèle

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

Répondre

2

Uri constructeur de classe est privé et il est une classe abstraite. Gson tente de créer un nouvel objet pour la classe Uri à l'aide de Reflection API (Nous ne pouvons pas créer d'objet pour une classe abstraite). Solution si simple est de changer le uriPath en String au lieu de Uri.

private String uriPath;