I have these codes which basically use a ListView to display the names in the contact list and I want to get their phone number when click each single name:
final ContentResolver cr = getContentResolver();
final Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {ContactsContract.Contacts.DISPLAY_NAME}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);
myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
c.moveToPosition(position);
Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), Toast.LENGTH_SHORT).show();
}
});
In the onItemClick
Method the
GetColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
returns -1 and therefore I cannot get the phone number with this method.
I've also tried to print out all the columns of the cursor c
and it returns 34 columns but the only column which seems to be related to the phone number is HasPhoneNumber
.
So where's the problem and how can I fix it? Thanks!
The updated version, where the String
array passed to construct myCursorAdapter
is changed:
final ContentResolver cr = getContentResolver();
final Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);
myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
c.moveToPosition(position);
Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), Toast.LENGTH_SHORT).show();
}
});
I suppose the updated code will show the phone numbers in the ListView but I got an error says "column 'data1' does not exist".