ArrayList的空指针异常 [英] ArrayList null pointer exception
问题描述
我已经创建了一个ArrayList和一个ListView。我打算通过ListView的迭代,并检查他们是否被选中与否,然后添加对象(使用ListView.getItem()),以我的数组列表。但是,我得到一个NullPointerException异常。 people_selected ArrayList中,在这样的类顶部声明:
的ArrayList< PeopleDetails> selected_people;
和我的code:
的for(int i = 0; I< people_list.getCount();我++){
item_view = people_list.getAdapter()getView(I,NULL,NULL);
chBox =(复选框)item_view.findViewById(R.id.checkBox); //你的XML值复选框ID。
如果(chBox.isChecked()){
selected_people.add((PeopleDetails)people_list.getItemAtPosition(一));
}
} 对于(PeopleDetails人:selected_people){ SmsManager短信= SmsManager.getDefault();
sms.sendTextMessage(person.number,空,sms_message,NULL,NULL);
}
///现在需要编写方文件。
我在该行得到一个错误
有关(PeopleDetails人:selected_people)
块引用>说NullPointerException异常
。我认为这意味着该ArrayList是空的,不能弄清楚为什么它应该为null。难道我宣布它错在我班上的第一名?或者是我的选择和添加方法有问题?感谢您的帮助! :)
解决方案的ArrayList< PeopleDetails> people_selected;
您声明并永远不会初始化。在使用它之前只是初始化。否则
NullPointerException异常
。尝试初始化它
的ArrayList< PeopleDetails> people_selected =新的ArrayList< PeopleDetails>();
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;
And my code:
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.
I get an error at the line
for(PeopleDetails person : selected_people)
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?
Thanks for the help!! :)
解决方案ArrayList<PeopleDetails> people_selected;
You declared and never initialized. Just initialize it before using it. Otherwise
NullPointerException
.Try to initialize it
ArrayList<PeopleDetails> people_selected= new ArrayList<PeopleDetails>();
这篇关于ArrayList的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!