AutoCompleteTextView直接与sqlite数据库绑定 实现模糊查询

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

转载于 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 
  1. SQLiteDatabase sqlite = this.openOrCreateDatabase("data", 0, null);
  2. //连接数据库
  3. AutoCompleteTextView actv=(AutoCompleteTextView) findViewById(R.id.actv);
  4. //不解释
  5. actv.setThreshold(1);
  6. //输入一个字符即开始匹配
  7. String[] trainColumns = new String[] {"train_no", "id as _id" };
  8. //欲查询匹配的列放第一,查询结果必须有_id列,因我的表中没有,所以把id as成_id,实践证明,其实随便哪个字段都可以as _id,不用主键,这里也可以train_no as _id.
  9. trainAdpter trainadpter = new trainAdpter(this, null, 0);
  10. //实例化自定义的适配器,代码在下面
  11. actv.setAdapter(trainadpter);
  12. //绑定适配器
  13.  
  14. private class trainAdpter extends CursorAdapter {
  15. private int columnIndex;
  16.  
  17. public trainAdpter(Context context, Cursor c, int col) {
  18. super(context, c);
  19. this.columnIndex = col;
  20. }
  21.  
  22. @Override
  23. public View newView(Context context, Cursor cursor, ViewGroup parent) {
  24. final LayoutInflater inflater = LayoutInflater.from(context);
  25. final TextView view = (TextView) inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
  26. return view;
  27. }
  28.  
  29. @Override
  30. public void bindView(View view, Context context, Cursor cursor) {
  31. ((TextView) view).setText(cursor.getString(columnIndex));
  32. }
  33.  
  34. @Override
  35. public String convertToString(Cursor cursor) {
  36. Log.i("info", " convertToString ");
  37. return cursor.getString(columnIndex);
  38. }
  39.  
  40. @Override
  41. public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
  42. if (constraint != null) {
  43. String selection = "train_no like \'%" + constraint.toString() + "%\' limit 100";
  44. System.out.println(selection);
  45. return sqlite.query("train", trainColumns, selection, null, null, null, null);
  46. //从表train查询
  47. } else {
  48. return null;
  49. }
  50. }
  51. }
  52.  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值