我正在使用带有here库的Prateek's RxPreferences所示的GsonPreferenceAdapter。
My Fragment Class Code:
@Inject RxSharedPreferences sharedPreferences;
@Inject Gson gson;
List<MyClass> my_class_list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Binding and Inject go here.
Class listType = new TypeToken<ArrayList<MyClass>>(){}.getClass();
GsonPreferenceAdapter<List<MyClass>> adapter = new GsonPreferenceAdapter<>(gson, listType, new ArrayList<MyClass>(), GsonPreferenceAdapter.SyntaxExceptionBehavior.NULL);
my_class_list = sharedPreferences.getObject("pref_myclass", new ArrayList<>(), adapter).get();
if(my_class_list == null)
Timber.i("Tis null.");
Timber.i("Printing MyClass items...");
for(MyClass item: my_class_list)
Timber.i("MyClass: " + item);
}
@OnClick(R.id.add)
public void add() {
MyClass entry = new MyClass("Count Dracula", "12345");
my_class_list.add(entry);
Class listType = new TypeToken<List<MyClass>>(){}.getClass();
GsonPreferenceAdapter<List<MyClass>> adapter = new GsonPreferenceAdapter<>(gson, listType, new ArrayList<MyClass>(), GsonPreferenceAdapter.SyntaxExceptionBehavior.NULL);
sharedPreferences.getObject("pref_myclass", new ArrayList<>(), adapter).set(my_class_list);
Timber.i("Data Saved");
return false;
}
当我第一次运行它时,它不会记录 Tis null ,这意味着my_class_list不为null。然后我点击按钮调用add(),这将返回数据已保存,表明它确实已保存。当我重新启动应用程序时,它会在for循环中崩溃:
Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
它还打印 Tis null ,所以我很惊讶如何添加null。这里发生了什么,以及如何解决这个问题?
MyClass的内容:
public class MyClass {
@SerializedName("name")
@Expose
public String name;
@SerializedName("number")
@Expose
public String number;
public MyClass(String name, String number) {
this.name = name;
this.number = number;
}
@Override
public String toString() {
return "MyClass{" +
"name='" + name + '\'' +
", number='" + number + '\'' +
'}';
}
}
答案 0 :(得分:0)
没关系,我自己想出来了。如果有其他人遇到同样的问题,我会给出答案。问题出在GsonPreferenceAdapter上,我扯掉了。我将Class更改为Type,一切正常。
Type type = new TypeToken<List<MyClass>>(){}.getType();
GsonPreferenceAdapter<List< MyClass >> adapter = new GsonPreferenceAdapter<>(gson, type, new ArrayList<>(), GsonPreferenceAdapter.SyntaxExceptionBehavior.NULL);
my_class_list = sharedPreferences.getObject("pref_myclass", new ArrayList<>(), adapter).get();