Reputation: 153
Im trying to get all contacts (name and phonenumber) from my mobile Phone to an String Array. I tried it with this part of Code but Im getting a error ...
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String aNameFromContacts[] = new String[contacts.getCount()];
String aNumberFromContacts[] = new String[contacts.getCount()];
int ij = 0;
int nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
int numberFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.NUMBER);
while(contacts.moveToNext()) {
String contactName = contacts.getString(nameFieldColumnIndex);
aNameFromContacts[ij] = contactName ;
String number = contacts.getString(numberFieldColumnIndex);
aNumberFromContacts[ij] = number ;
ij++;
contacts.close();
Here is the error:
08-31 18:09:09.031: E/CursorWindow(16317): Failed to read row 0, column -1 from a CursorWindow which has 109 rows, 44 columns.
How can I fix it or is there a better way ?
Upvotes: 1
Views: 377
Reputation: 7394
Always Use contacts.getColumnIndexOrThrow(PhoneLookup.NUMBER);
instead of contacts.getColumnIndex(PhoneLookup.NUMBER);
So that you can get exact error details. in this case which is:
java.lang.IllegalArgumentException: column 'number' does not exist
Means your are trying to get index of column which is not present so your getColumnIndex method is returning is null as expected.
Following piece of code will give you what you want:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
String aNameFromContacts[] = new String[cur.getCount()];
String aNumberFromContacts[] = new String[cur.getCount()];
int j = 0;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
if (("1")
.equals(cur.getString(cur
.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER)))) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
int i = 0;
int pCount = pCur.getCount();
String[] phoneNum = new String[pCount];
String[] phoneType = new String[pCount];
while (pCur.moveToNext()) {
phoneNum[i] = pCur
.getString(pCur
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType[i] = pCur
.getString(pCur
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.TYPE));
i++;
}
if (phoneNum.length > 0) {
aNumberFromContacts[i] = phoneNum[0];
aNameFromContacts[j] = name;
Log.d("name = ", "" + name +", phoneNumber = " + phoneNum[0]);
}
}
j++;
}
}
Also try to understand this code so you will understand how it is working and what is phoneNum and phoneType.
PS: This code can be optimize for better performance, as per need.
Upvotes: 1