使用OnItemClickListener为自动完成返回空的游标

时间:2012-02-08 05:57:47

标签: android cursor simplecursoradapter autocompletetextview indexoutofboundsexception

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

        }
    });

可能导致光标为空的原因是什么?

1 个答案:

答案 0 :(得分:1)

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