ArrayList空指针exception

我创建了一个arraylist和一个ListView。 我打算遍历ListView,并检查它们是否被选中,然后将对象(使用ListView.getItem())添加到我的arraylist。 但是我得到一个NullPointerException。 ArrayList people_selected,在类的顶部声明如下:

ArrayList selected_people; 

我的代码:

 for (int i = 0; i < people_list.getCount(); i++) { item_view = people_list.getAdapter().getView(i, null, null); chBox = (CheckBox) item_view.findViewById(R.id.checkBox);//your xml id value for checkBox. if (chBox.isChecked()) { selected_people.add((PeopleDetails) people_list.getItemAtPosition(i)); } } for(PeopleDetails person : selected_people){ SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(person.number, null, sms_message, null, null); } ///and now need to write party to file. 

我在线上得到一个错误

for(PeopleDetails person:selected_people)

说“NullPointerException”。 我认为这意味着arraylist是null,并且无法弄清楚为什么它应该为null。 我是否在课堂上声明错了? 或者我的选择和添加方法有问题?

 ArrayList people_selected; 

你宣布并且从未初始化。 只需在使用之前初始化它。 否则NullPointerException

尝试初始化它

 ArrayList people_selected= new ArrayList(); 

你错过了

 people_selected = new ArrayList(); 

你声明了它但没有初始化。

代码显示您声明了变量,但没有显示您对其进行初始化,如下所示:

 people_selected = new ArrayList(); 

您声明了people_selected,但您正在使用selected_people
哪个永远不会填补……

增强的for循环大致是这种结构

 for (Iterator i = someList.iterator(); i.hasNext();) { } 

未初始化的Collection ArrayList selected_people; 指的是null

如果在未初始化的Collection上启动增强的for循环,它将抛出NullPointerException因为它在null引用上调用了迭代器someList.iterator()

另一方面,如果你有一个像这样的初始化集合

 ArrayList selected_people = new ArrayList<>(); 

你会注意到增强的for循环不会抛出任何NullPointerException因为someList.iterator()现在返回一个迭代器而i.hasNext()返回false只是为了让循环不继续。

PS:增强的for循环骨架取自此处 。