private class MessageAddressAdapter extends CursorAdapter {
private final LayoutInflater inflater;
/*
* constraint 关键字
*/
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (TextUtils.isEmpty(constraint)) {
return null;
}
// 查询联系人号码
ContentResolver resolver = getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
// content://com.android.contacts/data/phones/
String[] projection = CONTACT_PROJECTION;
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER+" like '%"+ constraint+"%'";
//data1 like '%...%'
Cursor cursor = resolver.query(uri, projection, selection, null, null);
return cursor;
}
public MessageAddressAdapter(Context context, Cursor c,
boolean autoRequery) {
super(context, c, autoRequery);
inflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = inflater.inflate(R.layout.item_new_message, parent, false);
ViewHolder holder = new ViewHolder();
holder.tvContactName = (TextView) view.findViewById(R.id.tv_contact_name);
holder.tvContactAddress = (TextView) view.findViewById(R.id.tv_contact_address);
view.setTag(holder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
// 获得数据
String contactDisplayName = cursor.getString(DISPLAY_NAME_COLUMN_INDEX);
String contactNumber = cursor.getString(NUMBER_COLUMN_INDEX);
// 设置数据
holder.tvContactName.setText(contactDisplayName);
holder.tvContactAddress.setText(contactNumber);
}
}
分析:因为要加上一个唯一标识的主键,所以要加上一个_id
private static final String[] CONTACT_PROJECTION = new String[] {
ContactsContract.Contacts._ID,// java.lang.IllegalArgumentException: column '_id' does not exist
ContactsContract.Contacts.DISPLAY_NAME, // 练习人名称
ContactsContract.CommonDataKinds.Phone.NUMBER,// 联系人号码
};
private static final int NUMBER_COLUMN_INDEX = 1;
private static final int DISPLAY_NAME_COLUMN_INDEX = 2; ......
// 查询联系人号码
ContentResolver resolver = getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
// content://com.android.contacts/data/phones/
String[] projection = CONTACT_PROJECTION;
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER+" like '%"+ constraint+"%'";
//data1 like '%...%'
Cursor cursor = resolver.query(uri, projection, selection, null, null); 解决:进行数据库查询的时候,加上 ContactsContract.Contacts._ID就可以了
01-24 10:08:56.541: E/AndroidRuntime(1650): java.lang.IllegalArgumentException: column '_id' does not exist