Reputation: 504
I have been practicing on contacts reading in android and I am getting the contacts and the numbers but they are not arranged well. I mean the names assigned are not of the owners of the numbers. here is my code:
String [] projection= new String[]{ContactsContract.Contacts.DISPLAY_NAME,};
String [] phoneProjection= new String [] {Phone.NUMBER};
ContentResolver crInstance=getContentResolver();
final Cursor name=crInstance.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
final Cursor phone=crInstance.query(Phone.CONTENT_URI, phoneProjection, null, null, null);
contactview = (TextView) findViewById(R.id.contactview);
name.moveToFirst();
phone.moveToFirst();
while (!name.isAfterLast()&&!phone.isAfterLast()){
String pname=name.getString(name.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactview.append("Name:");
contactview.append(pname);
contactview.append("\n");
final int contactNoColIndex= phone.getColumnIndex(Phone.NUMBER);
String pnumber=phone.getString(contactNoColIndex);
contactview.append("Phone:");
contactview.append(pnumber);
contactview.append("\n");
contactview.append("\n");
name.moveToNext();
phone.moveToNext();
}
name.close();
phone.close();
please help
Upvotes: 1
Views: 2062
Reputation: 15046
Here is a simple way:
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.moveToFirst()) {
String name;
String phone;
while (cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// do what you want with the name and the phone number
}
} else {
Log.v(LOG_TAG, "Cursor is empty");
}
cursor.close();
Not forget to add permission into your manifest
Upvotes: 3
Reputation: 504
This code basically gets the Number first then uses it to search for the contact name.
`
Cursor c;
c= mydb.query("sms", null, null, null, null, null, null);
while (c.moveToNext()) {
String name = null;
String sender=c.getString(c.getColumnIndex("phoneNo"));
String time=c.getString(c.getColumnIndex("smstype"));
String smsbody=c.getString(c.getColumnIndex("message"));
String[] projection = new String[]{
ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contacturi= Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(sender));
ContentResolver cr = getContentResolver();
Cursor crc= cr.query(contacturi, projection, null, null, null);
if(crc.moveToNext()){ name=crc.getString(crc.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); } else{
name ="Unknown";
}
String senderid= name+" "+ sender;`
Upvotes: 1