Android: Failed to invoke private android.net.Uri() with no args

北战南征 提交于 2021-02-07 18:47:24

问题


I am saving my arraylist of custom model into shared preference using Gson

Storing code:

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

Retrieving

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
        }

But on the error line I'm getting: can't instantiate class 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;
    }
}

回答1:


Uri class constructor is private and it's an abstract class. Gson tries to create a new object for the Uri class using Reflection API(We can't create an object for abstract class). So simple solution is to change the uriPath into String instead of Uri.

 private String uriPath;



回答2:


meh, just exclude the problematic instance variable(s) from the serialization/deserialization process. Gson: How to exclude specific fields from Serialization without annotations



来源:https://stackoverflow.com/questions/46031104/android-failed-to-invoke-private-android-net-uri-with-no-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!