Checkout my code I have been doing some work on an sms application and I am trying now to match the address that has came with the sms with the number that has been stored in the contacts…
So far I was unable to match the contact and display the name of the sender because on emulator contains only two contacts… It matches the first one and displays its name while on phone it doesnot finds a single contact…
public List<String> getSMS() {
List<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,
null);
ContentResolver cr = getContentResolver();
Cursor contactsCur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
Cursor phoneCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
"DISPLAY_NAME = '" + name + "'", null, null);
Log.v(LOG_TAG, "going in loop");
if (contactsCur.getCount() > 0) {
Log.v(LOG_TAG, "inside loop");
while (contactsCur.moveToNext()) {
Log.v(LOG_TAG, "cursor moving to next");
id = contactsCur.getString(contactsCur
.getColumnIndex(ContactsContract.Contacts._ID));
Log.i(LOG_TAG,"this is id: " + id);
name = contactsCur
.getString(contactsCur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + id, null, null);
Log.i(LOG_TAG, "This is name "+name);
while (phones.moveToNext())
{
number = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
String aNumber=number.replaceAll("-", "");
Log.i(LOG_TAG,"this is number :"+aNumber);
Log.v(LOG_TAG, "getting address and message");
while (cur.moveToNext()) {
String address = cur.getString(cur
.getColumnIndex("address"));
if(address.equals(aNumber))
address=name;
String body = cur.getString(cur
.getColumnIndexOrThrow("body"));
sms.add("Number: " + address+ " .Message: " + body);
}
Log.v(LOG_TAG, "closing phone cursor");
phoneCur.close();
}
}
}
return sms;
}
I didn’t completely understood what you coded here.But I got your requirement.So my suggestion is-try this way(I haven’t tried it because of the lack of time for now,but logically it should work):
EDIT :
To group all sms from each contact: