ArrayList 空指针异常 [英] ArrayList null pointer exception
问题描述
我创建了一个数组列表和一个列表视图.我打算遍历 ListView,并检查它们是否被选中,然后将对象(使用 ListView.getItem())添加到我的数组列表中.但是我得到一个 NullPointerException.ArrayList people_selected,在类的顶部声明如下:
I have created an arraylist, and a ListView. I intend to iterate through the ListView, and checking whether they are checked or not, and then add the object (using ListView.getItem()) to my arraylist. however I get a NullPointerException. The ArrayList people_selected, is declared at top of class like this:
ArrayList<PeopleDetails> 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)
for(PeopleDetails person : selected_people)
说NullPointerException".我认为这意味着 arraylist 为空,并且无法弄清楚为什么它应该为空.我在班级最高处宣布错误了吗?还是我的选择和添加方法有问题?
Saying "NullPointerException" . I take this to mean that the arraylist is null, and cannot figure out why it should be null. Have I declared it wrong at the top of my class? Or is my selection and add method faulty?
推荐答案
ArrayList<PeopleDetails> people_selected;
您声明并从未初始化.只需在使用前初始化它.否则 NullPointerException
.
You declared and never initialized. Just initialize it before using it. Otherwise NullPointerException
.
尝试初始化
ArrayList<PeopleDetails> people_selected= new ArrayList<PeopleDetails>();
这篇关于ArrayList 空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!