Rafael Sanchez Rafael Sanchez - 2 years ago 348
Java Question

Error trying to use GSON with own class

I'm trying to use Google's GSON for the first time in my Android app. I want to use GSON with a class called

, which keeps most of my ArrayList, booleans, Strings and other basic objects in one place. My goal is to save an instance of
. I wrote:

Gson gson = new Gson();
String userValuesJSON=gson.toJson(userValues);
getSharedPreferences(myAppKey, MODE_PRIVATE).edit().putString("JSON", userValuesJSON).commit();

The error I get:

java.lang.SecurityException: Can't make method constructor accessible
at java.lang.reflect.Constructor.setAccessible(Constructor.java:336)
at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:97)
at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:79)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:71)
at com.google.gson.Gson.getAdapter(Gson.java:356)

when I added GSON I added the following to

repositories {

dependencies {
compile 'com.google.code.gson:gson:2.2.4'

Any brainstorming greatly appreciated!

EDIT: This is how the constructor looks like:

public class UserValues implements Serializable {

private Integer period;
private Float fee;
private ArrayList<Boolean> theBooleans = new ArrayList<>();
private ArrayList<Integer> theIntegers = new ArrayList<>();
private static final ArrayList<String> theIntegerKeys = new ArrayList<>();
private static final ArrayList<String> theBooleanKeys = new ArrayList<>();
public static final String myAppKey = "Investor Playground";
private static final ArrayList<Integer> theIntDefValues = new ArrayList<>();
private ArrayList<Float> arrayList;
private ArrayList<ArrayList<Integer>> theDates;
private ArrayList<Float> strategyResult;
private int theCurrentFragment;

private int theCurrentGraph;

Context context;

public UserValues(Context context_) {


Answer Source

add an empty constructor to the class as this will only be used to set values this should not cause any issues if the context is not initialised

public UserValues() {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download