男子大学生の考えること

日々思ったこと。プログラミング、音楽、アニメなど、、、

android AutoCompleteTextViewにSimpleCursorAdapterを使う

AutoCompleteTextViewを使うと、入力補完機能の付いたEditTextが使えます。(ちなみに、AutoCompleteTextViewはEditTextのサブクラス。EditTextはTextViewのサブクラス。何か違和感を感じますが。)
どう使うかというと、AutoCompleteTextView.setAdapter(Adapter adapter)といったように、AutoCompleteTextViewのインスタンスにArrayAdapterか何かをsetすればいいです。しかし、SimpleCursorAdapterを使うときはある処理が必要になってきます。
とりあえず普通に使ってみました。
ここで使うDatabaseは次のようなものとします。
f:id:gobopiyo:20141118233055p:plain

AutoCompleteTextView inputTextView = (AutoCompleteTextView) findViewById(R.id.autoInput);
		
		DatabaseOpenHelper helper = new DatabaseOpenHelper(this);
		SQLiteDatabase database = helper.getWritableDatabase();	
		Cursor cursor = database.query("person", new String[]{"rowid as _id", "name"}, null, null, null, null, null);
		CursorAdapter adapter = new SimpleCursorAdapter(
				this, 
				android.R.layout.simple_spinner_item,
				cursor,
				new String[]{"name"},
				new int[]{android.R.id.text1},
				0);
		inputTextView.setAdapter(adapter);

実行すると、、、、
f:id:gobopiyo:20141118233256p:plain
できたと思って候補をタッチすると、
f:id:gobopiyo:20141118233349p:plain
ええ、、、
ということで、次の処理をsetAdapter()の前にします。

adapter.setCursorToStringConverter(new CursorToStringConverter() {
			@Override
			public String convertToString(Cursor cursor) {
				return cursor.getString(cursor.getColumnIndex("name"));
			}
		});

おそらく、候補をタッチしたとき、内部ではタッチしたカーソルのtoString()を入力しているためこのようになってしまうようです。なので、タッチしたCursorからどのようにStringの値を得るのかをこちらで指定する必要があるということです。
今回はカラムnameの値のみを候補に表示しましたが、adapterをいじれば複数の値を表示できます。

これでうまくいきました。
f:id:gobopiyo:20141118234317p:plain