Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong reference to Contacts table from sms inbox

I am trying to find the contact details corresponding to an sms from the phone's sms inbox. From my understanding the person column is a foreign key to the _id column of ContactsContract.Contacts.

My problem is that I am getting wrong values for the person value from the sms query. Some person ids don't exist in the contact table and some are pointing to totally different contact.

Below is the code that I use for fetching the list of person values, Can anyone tell me if I missed something or faced a similar problem.

Tested with Nexus S running Android 4.1.2

Uri parsedUri = Uri.parse("content://sms/inbox");
    String[] projection = new String[] { "_id", "address", "person" };
    Cursor cursor = contentResolver.query(parsedUri, projection, null, null, null);

    Log.d(TAG, "Total Count " + cursor.getCount());

    if (cursor.getCount() > 0) {
        // String address;
        int person;
        int personIndex = cursor.getColumnIndex("person");
        if (cursor.moveToFirst())
            do {
                person = cursor.getInt(personIndex);
                if (person > 0) {
                    // Add this id to a list
                }
            } while (cursor.moveToNext());
    }
    cursor.close();

Update: I was looking at some documentation from the Android Developer Portal (http://developer.android.com/guide/topics/providers/contacts-provider.html), Is it possible that the person id that is retrieved from the sms inbox is referring to the ContactsContract.RawContacts instead of ContactsContract.Contacts as I have done.

like image 962
midhunhk Avatar asked Jan 30 '13 04:01

midhunhk


1 Answers

Indeed the person column in the sms inbox refers to a RawContacts entry's id. By querying the RawContacts table you can find the contact_id for the Contacts table for the specific user.

You can try this code to get the contact id from the RawContacts table..

long contactId = 0;
Uri uri = ContactsContract.RawContacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.RawContacts._ID, ContactsContract.RawContacts.CONTACT_ID };
Cursor cursor = contentResolver.query(uri, projection, 
        ContactsContract.RawContacts._ID + " = ?",
        new String[] { rawContactId }, null);

if (cursor.moveToFirst()) {
    int contactIdIndex = cursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID);
    contactId = cursor.getLong(contactIdIndex);
}
cursor.close();

This should solve your problem for fetching the correct contact details by reading an sms row in Android. However as the sms data provider is not documented and phone manufacturers may use them differently, there is chance that this approach may not work on phones other than pure android.

like image 179
akashPatra Avatar answered Oct 22 '22 10:10

akashPatra