Question

I am experiencing trouble with this code - it should not add duplicate strings in case it encounters some. I do not understand why it crashes.

Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
Temp = people.getString(NameIndex);
myArr.add(Temp.toString());

while (people.moveToNext()) {
    NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);    
    Name = people.getString(NameIndex);

    if((Name.toString()).equals(Temp)) {
    }
    else {
        myArr.add(Name.toString());
        Temp = Name.toString();
    }
}
Was it helpful?

Solution

You can use ArrayList's built-in function to check if the String is already present. Also, if the column doesn't exist, getColumnIndex() returns -1, and if that happens, you can't use it in the next line in getString(). So few modifications that you need are:

  • check if getColumnIndex() finds a column you are looking for
  • use ArrayList's build-in method to check whether a String is already there

Modified code:

while (people.moveToNext()) {
    NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);

    //check if we have a valid column index
    if (NameIndex != -1) {
        Name = people.getString(NameIndex);

        if(myArr.contains(Name)) {
            // do nothing, as the same String is already in the list
        }
        else {
            myArr.add(Name.toString());
        }
    }    
}

NOTE: it is a Java convention to start variable names with lower-case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top