【问题标题】:Cursor returning empty with OnItemClickListener for AutoComplete光标返回空并使用 OnItemClickListener 进行自动完成
【发布时间】:2012-02-08 05:57:47
【问题描述】:

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

        }
    });

什么可能导致光标为空?

【问题讨论】:

    标签: android cursor simplecursoradapter autocompletetextview indexoutofboundsexception


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 2012-01-14
      • 2013-03-08
      相关资源
      最近更新 更多