How to filter results of AutoCompleteTextView?

微笑、不失礼 提交于 2019-11-28 19:49:51

Construct a FilterQueryProvider and pass it into adapter.setFilterQueryProvider().

adapter.setFilterQueryProvider(new FilterQueryProvider() {
    public Cursor runQuery(CharSequence constraint) {
        String s = '%' + constraint.toString() + '%';
        return getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
            new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER},
            Phone.DISPLAY_NAME + ' LIKE ? OR ' + Phone.NUMBER + ' LIKE ?',
            new String[] { s, s },
            null);
    }
});

The code above will return results that match anywhere in the string (not just in the beginning. Also, since it uses parameterized queries, your users won't be able to damage the DB via a SQL injection attack.

(Not near an actual computer, so I can't test the above -- probably some syntax errors in there.)

Finally tried something that worked:

private void initViews() {

    edt_Contact = (AutoCompleteTextView)findViewById(R.id.compose_edtContact);

    cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
            new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, 
            null,null,null);
    startManagingCursor(cursor);
    String[] from = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER};
    int[] to = new int[] { R.id.contact_name, R.id.contact_phoneNo};
    adapter = new SimpleCursorAdapter(this, R.layout.simple_contact_textview, cursor, from, to);

    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                    new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, 
                    Phone.DISPLAY_NAME + " LIKE '" + constraint + "%'", 
                    null, null);
        }
    });

    edt_Contact.setAdapter(adapter);
}

Sorry if I robbed anyone of an answer. All questions like this seem to have very low views and answers...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!