gpt4 book ai didi

java - NullPointerException 即使没有什么是空的?

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:58 25 4
gpt4 key购买 nike

我查看了所有代码,但找不到任何空引用,所以我迷路了。我将用户收集的某些联系人保存到共享首选项中:

   public void saveContacts() {

contacts = this.getSharedPreferences("contacts", MainActivity.MODE_PRIVATE); //Making a shared preferences

Set<String> set = new HashSet<String>();
set.addAll(contactArrayList);

contactEditor.clear(); //Clearing current values in shared pref
contactEditor.putStringSet("contactSetKey", set); //Adding contacts
contactEditor.commit();

Toast.makeText(MainActivity.this, "Contacts have been saved!", Toast.LENGTH_SHORT).show();
}

这里是我获取联系人的地方:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


contactArrayList= new ArrayList<String>();
listview = (ListView) findViewById(R.id.listView);

arrayAdapter = new ArrayAdapter (this, android.R.layout.simple_list_item_1, contactArrayList);
listview.setAdapter(arrayAdapter);

loadSavedStuff();


}

public void loadSavedStuff() {
//CLEAR CONTENTS OF ARRAYLIST AND GET THEM FROM SHARED PREFERENCE


if(contacts.getStringSet("contactSetKey", null) != null) {
contactArrayList.clear();
contactArrayList = new ArrayList<String>(contacts.getStringSet("contactSetKey", null));
arrayAdapter.notifyDataSetChanged();
}
}

我一直在像这样向列表中添加内容:

  contactArrayList.add(contactName +" - " +contactNumber);
arrayAdapter.notifyDataSetChanged();

我的空指针异常在这里:

  Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set android.content.SharedPreferences.getStringSet(java.lang.String, java.util.Set)' on a null object reference

指向这里:

    if(contacts.getStringSet("contactSetKey", null) != null) {

这里:

    loadSavedStuff();

最佳答案

您只检查 getStringSet 是否不是 null,而 contacts 仍然可以是 null,这就是为什么它会抛出 NullPointerException

改变

if(contacts.getStringSet("contactSetKey", null) != null) {

if(contacts != null && (contacts.getStringSet("contactSetKey", null) != null)) {

关于java - NullPointerException 即使没有什么是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35107587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com