Swedish Architect Swedish Architect - 3 months ago 7x
Java Question

ArrayList null pointer exception

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?

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