AutoCompleteTextView数据库读取

本文介绍了如何将数据库数据与Android的AutoCompleteTextView关联,通过自定义CursorAdapter实现当输入时动态查询数据库并显示建议。重点讲解了自定义适配器的编写和使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 AutoCompleteTextView从数组里面读取数据很简单,只需使用默认适配器即可,下面我们简单介绍如何将数据库与AutoCompleteTextView关联起来。

1、自定义适配器

public class MyCursorAdapter extends CursorAdapter {
 private LayoutInflater layoutInflater;

 public MyCursorAdapter(Context context, Cursor c,boolean autoRequery) {
  super(context, c, autoRequery);
  layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
 }
 private void setView(View view, Cursor cursor)
 {
  TextView tvWordItem = (TextView) view;
  tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));
 }
 @Override
 public void bindView(View view, Context context, Cursor cursor) {
  // TODO Auto-generated method stub
  setView(view, cursor);
 }

 @Override
 public View newView(Context context, Cursor cursor, ViewGroup parent) {
  // TODO Auto-generated method stub
  final LayoutInflater inflater = LayoutInflater.from(context);
        final TextView view = (TextView) inflater.inflate(
                android.R.layout.simple_dropdown_item_1line, parent, false);
        setView(view, cursor);
        return view;
 }
 
 @Override
 public CharSequence convertToString(Cursor cursor) {
  // TODO Auto-generated method stub
  return cursor == null?"":cursor.getString(cursor.getColumnIndex("_id"));
    
 }

}

2、调用方式

AutoCompleteTextView actv_lighttype = (AutoCompleteTextView) findViewById(R.id.actv_lighttype);

actv_lighttype.addTextChangedListener(new TextWatcher() {
   
   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub
    
   }
   
   @Override
   public void beforeTextChanged(CharSequence s, int start, int count,
     int after) {
    // TODO Auto-generated method stub
    
   }
   
   @Override
   public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    String sqlStr="select 某列 as _id from 表名 where 某列 like '"+s.toString()+"%'";
    Cursor cursor=dbhelper.getAllRecordsBySql(sqlStr);
    MyCursorAdapter bltcadapter = new MyCursorAdapter(XXXX.this,cursor,true);
    actv_lighttype.setAdapter(bltcadapter);
   }
  });

通过以上重写的适配器,我们可以稍微了解了SimpleCursorAdapter为什么非要有_id字段了吧,及其参数为什么要那样设置了吧。又或者我们可以编写自己的SimpleCursorAdapter了!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值