AutoCompleteTextView绑定数据库,模糊匹配方法 使用CursorAdapter

通过CursorAdapter这个适配器,AutoCompleteTextView可以直接与sqlite数据库绑定,而不用在程序中预先添加匹配数据。并且,通过sql的like关键字,可以实现模糊查询,非首字母查询。
贴上代码:


SQLiteDatabase sqlite = this.openOrCreateDatabase("data", 0, null);
//连接数据库
AutoCompleteTextView actv=(AutoCompleteTextView) findViewById(R.id.actv);
//不解释
actv.setThreshold(1);
//输入一个字符即开始匹配
String[] trainColumns = new String[] {"train_no", "id as _id" };
//欲查询匹配的列放第一,查询结果必须有_id列,因我的表中没有,所以把id as成_id,实践证明,其实随便哪个字段都可以as _id,不用主键,这里也可以train_no as _id.
trainAdpter trainadpter = new trainAdpter(this, null, 0);
//实例化自定义的适配器,代码在下面
actv.setAdapter(trainadpter);
//绑定适配器

private class trainAdpter extends CursorAdapter {
		private int columnIndex;

		public trainAdpter(Context context, Cursor c, int col) {
			super(context, c);
			this.columnIndex = col;
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final LayoutInflater inflater = LayoutInflater.from(context);
			final TextView view = (TextView) inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
			return view;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			((TextView) view).setText(cursor.getString(columnIndex));
		}

		@Override
		public String convertToString(Cursor cursor) {
			Log.i("info", " convertToString ");
			return cursor.getString(columnIndex);
		}

		@Override
		public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
			if (constraint != null) {
				String selection = "train_no like \'%" + constraint.toString() + "%\' limit 100";
				System.out.println(selection);
				return sqlite.query("train", trainColumns, selection, null, null, null, null);
				//从表train查询
			} else {
				return null;
			}
		}
	}

© 2011, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记