【发布时间】:2016-04-20 20:49:45
【问题描述】:
我第一次尝试在我的 Android 应用中使用 Google 的 GSON。我想将 GSON 与一个名为 UserValues 的类一起使用,它将我的大部分 ArrayList、布尔值、字符串和其他基本对象保存在一个地方。我的目标是将UserValues 的实例保存到SharedPreferences。我写道:
Gson gson = new Gson();
String userValuesJSON=gson.toJson(userValues);
getSharedPreferences(myAppKey, MODE_PRIVATE).edit().putString("JSON", userValuesJSON).commit();
我得到的错误:
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)
当我添加 GSON 时,我将以下内容添加到 build.gradle:
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.code.gson:gson:2.2.4'
}
非常感谢任何头脑风暴!
编辑:这是构造函数的样子:
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_) {
context=context_;
...
}
【问题讨论】:
-
该错误表明 UserValues (
public UserValues () {}) 的默认构造函数不可访问。这是因为一个不存在,或者它被标记为私有。
标签: java android gson android-sharedpreferences