Курсор возвращается пустым с OnItemClickListener для автозаполнения - PullRequest
0 голосов
/ 08 февраля 2012

Я использую встроенный AutoCompleteTextView и создаю его выпадающий список с этим кодом:

autoComp = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
    Uri filterUri;
    if (filterText == null) {filterUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;}else{filterUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(filterText + "%"));}
    String[] projection    = new String[] {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER};
    Cursor people = getContentResolver().query(filterUri, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    startManagingCursor(people);
    sca = new SimpleCursorAdapter(this, R.layout.autotextitem, people, 
            new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}, 
            new int[] {R.id.textView1, R.id.textView2});
    autoComp.setAdapter(sca);
    autoComp.setThreshold(0);

Когда пользователь выбирает элемент из выпадающего меню, я получаю исключение Курсор за пределами границ."CursorIndexOutOfBoundsException: индекс 0 запрошен, с размером 0"

Вот мой код, объявляющий OnClickEvent внутри метода onCreate для моей деятельности:

        autoComp.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> listView, View view,
                    int position, long id) {

            // Get the cursor, positioned to the corresponding row in the
            // result set
            Cursor cursor = (Cursor) sca.getItem(position);
            // Get the state's capital from this row in the database.
            String name =
                cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            // Update the parent class's TextView
            TextView textViewTo = (TextView) findViewById(R.id.textViewNames);
            textViewTo.setText((CharSequence) cursor);

        }
    });

Что может быть причиной того, что курсорбыть пустым?

1 Ответ

1 голос
/ 16 мая 2012

Попробуйте cursor.moveToFirst ();затем cursor.getString (cursor.getColumnIndexOrThrow (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

...