日期:2014-05-16  浏览次数:20433 次

AutoCompleteTextView连接到数据库
     AutoCompleteTextView可以根据输入的文字来显示提示, 它的Adapter可以是一个list, 也可以动态的提取数据库数据.
写了一个例子来展示, 建立一个数据库来储存人名, 只要在AutoCompleteTextView里面输入2个字母就会显示匹配下拉单.
这是一个定制的CursorAdapter, newView会返回一个包含cursor里文字的view, bindView把cursor的数据绑定在view里, convertToString会把view的数据转换为AutoCompleteTextView显示的文字, runQueryOnBackgroundThread方法会查询数据库.
private class MyCursorAdpter extends CursorAdapter {  
     private int columnIndex;  
       
     public MyCursorAdpter(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);  
         view.setText(cursor.getString(columnIndex));  
         return view;  
     }  
     @Override  
     public void bindView(View view, Context context, Cursor cursor) {  
         ((TextView) view).setText(cursor.getString(columnIndex));  
     }  
       
     @Override  
     public String convertToString(Cursor cursor) {  
         return cursor.getString(columnIndex);  
     }  
     @Override  
     public Cursor runQueryOnBackgroundThread(CharSequence constraint) {  
         if (constraint != null) {  
             String selection = "name like \'" + constraint.toString() +"%\'";  
             return sqlite.query("test", columns, selection, null, null, null, null);  
         }  
         else {  
             return null;  
         }  
     }  
 }  

建立数据库, 以及添加数据, 使用CursorAdapter的数据库必须包含_id项.
private void createDatas() {  
    String createTable = "create table test (name varchar(255), _id varchar(255))";  
    sqlite.execSQL(createTable);  
      
    ContentValues values = new ContentValues();  
    values.put("name", "nicole");  
    values.put("_id", "0");  
    sqlite.insert("test", null, values);  
      
    values.put("name", "nicolas");  
    values.put("_id", "1");  
    sqlite.insert("test", null, values);  
      
    values.put("name", "jean");  
    values.put("_id", "2");  
    sqlite.insert("test", null, values);  
      
    values.put("name", "jennyfer");  
    values.put("_id", "3");  
    sqlite.insert("test", null, values);  
}  
1 楼 hunanxtww 2011-08-18  
您的文章很好,很强大。。。。