Skip to content Skip to sidebar Skip to footer

Get Contact List In An Array

Cursor c; ArrayList> list = new ArrayList>(); c=getContentResolver().query(ContactsContract.

Solution 1:

String[] name = newString [10000]{};
while (c.moveToNext()){
     .....
.  .. . ..
 .. . 

name[i] = displayName;
i++;
}

Log.d("COUNTS_CONTACTS", Arrays.toString(name));

Output :

[B, Bs, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, .....]

I wasn't actually declaring array size. So, when I added array size. Then, print out again it was working fine.!

Solution 2:

I would not recommend guessing the array size you'll need for two reasons:

  1. Your app may crash if it runs on a device with more then 10,000 contacts
  2. You're allocating a huge string array, even if the number of contacts is very small

The best approach would be to start with an ArrayList (which has flexible length), and then convert it to the String array you need.

Also, it's advised to add a projection to all your queries to make them faster and use less memory.

// Start with an ArrayList as we don't know the size we'll needList<String> names = newArrayList<>();

String[] projection = newString[] { Phone.DISPLAY_NAME, Phone.NUMBER};
Cursor c = getContentResolver().query(Phone.CONTENT_URI,projection,null,null,DISPLAY_NAME + " ASC ");

while (c.moveToNext()){
    String displayName = c.getString(0);
    Stringnumber = c.getString(1);

    names.add(displayName);
    Log.d("CONTACTS_NAME", "Found: " + displayName + ", with number " + number);
}

c.close();

// convert the ArrayList to a String arrayString[] namesArr = names.toArray(newString[]);

Post a Comment for "Get Contact List In An Array"