ArrayList空指针异常

Swe*_*ect 1 java android listview arraylist nullpointerexception

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

ArrayList<PeopleDetails> selected_people;
Run Code Online (Sandbox Code Playgroud)

我的代码:

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.
Run Code Online (Sandbox Code Playgroud)

我在线上得到一个错误

for(PeopleDetails person:selected_people)

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

Sur*_*tta 15

ArrayList<PeopleDetails> people_selected;
Run Code Online (Sandbox Code Playgroud)

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

尝试初始化它

ArrayList<PeopleDetails> people_selected= new ArrayList<PeopleDetails>();
Run Code Online (Sandbox Code Playgroud)


Bla*_*elt 7

你错过了

people_selected = new ArrayList<PeopleDetails>();
Run Code Online (Sandbox Code Playgroud)

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