-3

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;
    }

}
Arslan Ali
  • 33
  • 1
  • 8

1 Answers1

-2

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;
}
sixones
  • 1,953
  • 4
  • 21
  • 25
  • Maybe... But it will not fix npe – Selvin May 30 '16 at 22:23
  • Provide more information then ... Are you sure contacts exist and the issue is actually with adding `info` to `selectedContacts`? – sixones May 30 '16 at 22:24
  • yes contacts exist and issue is only while adding them – Arslan Ali May 30 '16 at 22:26
  • Body of while loop doesn't matter as obviously npe is in conditions check – Selvin May 30 '16 at 22:27
  • Something is probably resetting `selectedContacts` if you are getting a null exception when adding. ArrayLists wont be checking your `ContactInfo` and verifying anything there. So either your loop is wrong, and `contacts` doesnt exist or `selectedContacts` is being set to null in other parts of your code. – sixones May 30 '16 at 22:29
  • thanks @sixones by Declaring and initializing selectedContacts inside the function has solved the problem (y) – Arslan Ali May 30 '16 at 22:30
  • Glad to be of help! – sixones May 30 '16 at 22:30