ArrayList null pointer exception

丶灬走出姿态 提交于 2020-01-03 03:17:08

问题


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?


回答1:


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>();



回答2:


you missed

people_selected = new ArrayList<PeopleDetails>();

you have declared it but not intialized.




回答3:


The code shows that you declare the variable but doesn't show that you initialize it, like this:

people_selected = new ArrayList<PeopleDetails>();



回答4:


You declared people_selected but you're using selected_people?!
Which is never filled...




回答5:


The enhanced for loop is roughly of this structure

for (Iterator<T> i = someList.iterator(); i.hasNext();) {

}

An un-initialized Collection ArrayList<PeopleDetails> selected_people; refers to null.

If you start an enhanced for loop on an un-initialized Collection it will throw NullPointerException because of the fact that it calls the iterator someList.iterator() on the null reference.

On the other hand if you have an initialized Collection like so

ArrayList<PeopleDetails> selected_people = new ArrayList<>();

you will notice that the enhanced for loop doesn't throw any NullPointerException because of the fact that someList.iterator() now returns an iterator and i.hasNext() returns false just so that the loop doesn't proceed.

PS: The enhanced for loop skeleton is taken from here.



来源:https://stackoverflow.com/questions/21349733/arraylist-null-pointer-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!