Question

I am trying to get a listview containing the name and birtday of all the contacts:

in my oncreate():

final ListView listview = (ListView) findViewById(R.id.ListView1);
Cursor cursor=getContactsBirthdays();
SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,
    android.R.layout.two_line_list_item, cursor, 
    new String[] {ContactsContract.Contacts.DISPLAY_NAME, 
                  ContactsContract.CommonDataKinds.Event.START_DATE},
    new int[]{android.R.id.text1, android.R.id.text2});
listview.setAdapter(adapter);

My getContactsBirthdays() method:

private Cursor getContactsBirthdays() {
        try {
            Uri uri = ContactsContract.Data.CONTENT_URI;

            String[] projection = new String[] {
                    ContactsContract.Contacts.DISPLAY_NAME,
        //          ContactsContract.CommonDataKinds.Event.CONTACT_ID,
                    ContactsContract.CommonDataKinds.Event.START_DATE
            };

            String where = ContactsContract.Data.MIMETYPE + "= ? AND " +
                           ContactsContract.CommonDataKinds.Event.TYPE + "=" + 
                           ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
            String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
            return managedQuery(uri, projection, where, null, sortOrder);
        } catch (Exception e) {
            Log.e("Contact Error", "Error: " + e.getMessage());
            return null;
        }
    }

But i have an illegal argument exception: column '_id' does not exist When i create the adapter.

Can someone explain me why?

Was it helpful?

Solution 2

I finaly changed my code for this:

private Cursor getContactsBirthdays() {
    try {
        Uri uri = ContactsContract.Data.CONTENT_URI;

        String[] projection = new String[] {
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID,
                ContactsContract.CommonDataKinds.Event.START_DATE
        };
        String where =
                ContactsContract.Data.MIMETYPE + "= ? AND " +
                ContactsContract.CommonDataKinds.Event.TYPE + "=" + 
                ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
        String[] selectionArgs = new String[] { 
            ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
        };
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
        return managedQuery(uri, projection, where, selectionArgs, sortOrder);
    } catch (Exception e) {
        Log.e("Contact Error", "Error: " + e.getMessage());
        return null;
    }
}

OTHER TIPS

From the docs for CursorAdapter (which SimpleCursorAdapter extends):

The Cursor must include a column named "_id" or this class will not work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top