简单光标适配器出错,无法正常工作

时间:2012-04-30 14:09:00

标签: android

Cursor searchCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        new String[] {"_id",Phone.DISPLAY_NAME}, Phone.DISPLAY_NAME + " like ?", 
        new String[]{ "%" + cc.get("contactName").toString() + "%"}, null);

startManagingCursor(searchCursor);
while(searchCursor.isAfterLast() == false) {
    final String name = searchCursor.getString(searchCursor.getColumnIndex(Phone.DISPLAY_NAME));
    final String number = searchCursor.getString(searchCursor.getColumnIndex(Phone.NUMBER));
    str =new String[]{name,number};
    ada = new SimpleCursorAdapter(this, R.layout.view_contacts_listview_layout, searchCursor, str, new int[] { R.id.contactName, R.id.contactPhoneNo });
}

lvSearch.setAdapter(ada);

游标查询运行正常只会在简单的游标适配器中出现问题。

1 个答案:

答案 0 :(得分:1)

str =new String[]{name,number};

应该是

str = new String[]{Phone.DISPLAY_NAME, Phone.NUMBER};

您应该将列名称传递给SimpleCursorAdapter。相反,您将列值(例如555-555-5555,“john”)作为要使用的列名称传递

此外,您的代码可以简化为:

Cursor searchCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[] {"_id",Phone.DISPLAY_NAME}, Phone.DISPLAY_NAME + " like ?", 
                 new String[]{ "%" + cc.get("contactName").toString() + "%"}, null);

startManagingCursor(searchCursor);
str = new String[]{Phone.DISPLAY_NAME, Phone.NUMBER};
ada = new SimpleCursorAdapter(this,
                                R.layout.view_contacts_listview_layout, searchCursor,
                                str, new int[] {
                                        R.id.contactName, R.id.contactPhoneNo });

在将光标发送到SimpleCursorAdapter之前没有理由访问它。它将自动管理您需要的一切。

我还注意到,您只是在查询中选择了联系人_ID和DISPLAY_NAME,尽管您尝试访问SimpleCursorAdapter中的NUMBER ..您应该修改您的投影以包含电话号码。 例如:

String[] projection = new String[] { BaseColumns._ID, Phone.DISPLAY_NAME, Phone.NUMBER };

Cursor searchCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    projection , Phone.DISPLAY_NAME + " like ?", 
                     new String[]{ "%" + cc.get("contactName").toString() + "%"}, null);