在android listview中获取联系人姓名和生日

时间:2013-11-06 03:15:12

标签: android listview contacts simplecursoradapter

我正在尝试获取包含所有联系人名称和生日的列表视图:

在我的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);

我的getContactsBirthdays()方法:

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;
        }
    }

但我有一个非法的参数例外:列'_id'不存在 当我创建适配器时。

有人能解释我为什么吗?

2 个答案:

答案 0 :(得分:1)

来自the docs for CursorAdapterSimpleCursorAdapter延伸):

  

Cursor必须包含名为“_id”的列,否则此类将无效。

答案 1 :(得分:0)

我终于改变了我的代码:

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;
    }
}