带有CursorAdapter的AutoCompleteTextView适用于虚拟设备,但不适用于物理设备

时间:2015-07-21 20:40:24

标签: android android-contacts autocompletetextview android-cursoradapter

这个AutoCompleteTextView工作正常,直到我创建了一个FilterQueryProvider并将其传递给我的Adapter的setFilterQueryProvider方法。基本上我想要做的就是让用户输入联系人的姓名或电话号码,并显示相关的联系人。这是我的相关代码:

    //Set up the behavior for the recipient field.
    AutoCompleteTextView destination = (AutoCompleteTextView) findViewById(R.id.destination_number);

    //Get the list of contacts, add it to an array adapter.
    /*
    ArrayList<String>[] contactNames = getContactList();
    ArrayList<String> contactNumbers = getContactNumbers(contactNames[1]);
    */

    //Initialize the CursorAdapter.
    final ContentResolver cr = getContentResolver();
    Cursor nameCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE},
            ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "> 0", null, null);

    CompleteCursorAdapter mAdapter = new CompleteCursorAdapter(NewMessageActivity.this, nameCursor, false);

    nameCursor.close();

    FilterQueryProvider filter = new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {
            String query = "(instr(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +
                    ", '" + constraint + "') > 0 OR instr(" +
                    ContactsContract.CommonDataKinds.Phone.NUMBER
                    + ", '" + constraint + "') > 0) AND " + ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "> 0";

            return cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE},
                    query, null, null);
        }
    };

    mAdapter.setFilterQueryProvider(filter);
    destination.setAdapter(mAdapter);
    destination.setThreshold(2);

CompleteCursorAdapter只是CursorAdapter的一个简单扩展版本,到目前为止它一直运行良好。我假设因为我在我测试的虚拟设备上只有几个联系人,而在我的实际手机上只有100个联系人,我认为查询只是花了太长时间,并且它被系统杀死了。

然而,即使我在这个思路中纠正,我也不确定我能做些什么来解决这个问题。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

嗯,这很奇怪。事实证明我的手机必须运行旧版本的SQLite,因为它不知道如何处理instr()。我能够使用LIKE语句来解决这个问题。