Java – Android: Cannot call private without parameters android.net.Uri()

Android: Cannot call private without parameters android.net.Uri()… here is a solution to the problem.

Android: Cannot call private without parameters android.net.Uri()

I’m using Gson to save an array list of custom models to a shared preference

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

Retrieve

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 get: Unable to instantiate class android.net.Uri

Model number

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

Solution

The Uri class constructor is private, it is an abstract class. Gson tries to create a new object for the Uri class using the reflection API (we can’t create an object for an abstract class). Such a simple solution is to change the uriPath to a String instead of a URI.

 private String uriPath;

Related Problems and Solutions