Arslan Ali Arslan Ali - 6 months ago 13
Android Question

JavaNullPointer Exception on ArrayList Add Function

Hope you are doing well

i am facing issue while adding object to ArrayList
i need your kind assistance in solving this problem
each time when i am going to add something to selectedContacts ArrayList i got nullPointerException

ArrayList<ContactInfo> selectedContacts = new ArrayList<>();
public ArrayList<ContactInfo> getSelectedContacts()
{
int i = 0;
while (contacts.get(i).isCheck()==true)
{
ContactInfo info = contacts.get(i);
if(info != null)
selectedContacts.add(info);
i++;
}
return selectedContacts;
}


ContactInfo.Java

public class ContactInfo {
String name;
String number;
String email;
boolean check;

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public void setCheck(boolean check) {
this.check = check;
}

public void setName(String name) {
this.name = name;
}

public void setNumber(String number) {
this.number = number;
}

public boolean isCheck() {
return check;
}

public String getName() {
return name;
}

public String getNumber() {
return number;
}

}

Answer

Since your returning selectedContacts in your getSelectedContacts method, you would be better moving the ArrayList declaration inside your method. Such as;

public ArrayList<ContactInfo> getSelectedContacts()
{
    ArrayList<ContactInfo> selectedContacts = new ArrayList<>();

    int i = 0;
    while (contacts.get(i).isCheck()==true)
    {
        ContactInfo info = contacts.get(i);
        if(info != null)
            selectedContacts.add(info);
        i++;
    }
    return selectedContacts;
}
Comments