我正在尝试从共享首选项中获取数据并将该数据插入到列表中,但出现错误。虽然我已经初始化了列表,但仍然出现此错误
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
Information info = new Information(name, mobile, email, zone, type);
List<Information> listItems = new ArrayList<>();
SharedPrefManager sharedPrefManager = new SharedPrefManager(getActivity());
listItems = sharedPrefManager.getDataFromSharedPreferences("info");
listItems.add(info);
sharedPrefManager.setDataToSharedPreferences("info", listItems);
这是我的 SharedPrefManager getData 函数
public List<Information> getDataFromSharedPreferences(String key) {
Gson gson = new Gson();
SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String jsonPreferences = sharedPref.getString(key, null);
Type type = new TypeToken<List<Information>>() {
}.getType();
List<Information> contactList = gson.fromJson(jsonPreferences, type);
return contactList;
}
最佳答案
String jsonPreferences = sharedPref.getString(key, null);
是有问题的行。第二个参数(传递 null
的地方)是“def”参数,即如果没有存储与指定键匹配的首选项,则 getString()
返回的内容.
由于可能未设置首选项,因此 jsonPreferences
可能为 null(此处就是这种情况)。也就是说
List<Information> contactList = gson.fromJson(jsonPreferences, type);
将失败,因为您不能从空引用创建任何对象; Gson 正在尝试解析空字符串。
您应该在您的 jsonPreferences
赋值下方添加一个空检查:
String jsonPreferences = sharedPref.getString(key, null);
if (jsonPreferences == null || jsonPreferences.isEmpty()) return new ArrayList<Information>(); //return an empty list if there's no data; also checking for an empty String
关于android - bool java.util.List.add(java.lang.Object),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937776/