0

我正在使用内置的 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);

当用户从下拉列表中选择一个项目时,我收到一个 Cursor out of bounds 异常。“CursorIndexOutOfBoundsException:请求索引 0,大小为 0”

这是我在我的活动的 onCreate 方法中声明 OnClickEvent 的代码:

        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);

        }
    });

什么可能导致光标为空?

4

1 回答 1

1

尝试 cursor.moveToFirst(); 然后 cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

于 2012-05-16T07:43:05.823 回答