Android : Get contact phone number by ID - empty Cursor

on Wednesday, September 17, 2014


So I'm having trouble getting the phone number of a contact using its id.


This is the code I'm using to retrieve the number:



public String getNumber(){
//gets numbers by id
if (hasPhoneNumber){

ContentResolver contentResolver=context.getContentResolver();
Cursor cursor=contentResolver.query(
ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts._ID+" = "+id,
null,
null
); //TODO : resolve empty cursor error
//contact seems to have no data available?

if (cursor.moveToFirst()){

cursor.moveToNext();

String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

Cursor phones=contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+contactId,
null,
null);

if (phones.moveToFirst()){
while (phones.moveToNext()) {
this.number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}

phones.close();
} else {
test("cursor error...");
}

cursor.close();

return number;
} else {
return null;
}
}


It works with a few contacts but most show the "cursor error..." Toast (test("cursor error...") )


It's always the



Cursor cursor



that has the error.


My guess is it's empty but I know I have those contacts phone numbers saved. How do I fix this? Are there other values I have to request?


Thanks in advance!


0 comments:

Post a Comment