• AutoCompleteTextView 与sqlite绑定实现记住用户输入的内容并自动提示


    把用户输入的内容保存到数据库表中,然后用户输入时,进行模糊查询并把查询结果附到AutoCompleteTextView中。

    1:activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        xmlns:tools="http://schemas.android.com/tools"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        android:orientation="vertical" >  
          
        <AutoCompleteTextView  
                android:id="@+id/actValue"  
                android:layout_width="match_parent"  
                android:layout_height="wrap_content" 
                android:completionThreshold="1"
                android:singleLine="true"/>        
                
        <Button 
            android:id="@+id/btnClick"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Click"/>
      
          
    </LinearLayout>  

    2:DbUtil.java

    package com.example.autotest;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DbUtil extends SQLiteOpenHelper {
        private static final int DATABASE_VERSION = 10;        //当前数据库版本
        private static final String DATABASE_NAME = "wzh.db";
        
        private static final String TABLE_AUTO = "auto";    //国税邮件表
        
        private static final String CREATE_TABLE_AUTO_SQL = "create table " +
                TABLE_AUTO + "( _id integer primary key autoincrement, "+
                              " value varchar)";
        
        
        public DbUtil(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        
        /*
         * 数据库第一次被创建时调用onCreate
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE_AUTO_SQL);
        }
        
        /*
         * 如果 DATABASE_VERSION 改变 系统会调用onUpgrade
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        
            db.execSQL("drop table if exists " + TABLE_AUTO);
    
            onCreate(db);
        }
    }

    3:DBManager.java

    package com.example.autotest;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    public class DBManager {
        private DbUtil dbUtil = null;
        private SQLiteDatabase db = null;
        
        public DBManager(Context context){
            dbUtil = new DbUtil(context);
            db = dbUtil.getWritableDatabase();
        }
        
        public boolean valueExist(String value){
            int count = 0;
            Cursor c = db.rawQuery("select _id from auto where value = ?", 
                        new String[]{value});
            if(c.moveToNext()){
                count = c.getInt(c.getColumnIndex("_id"));
            }
            c.close();
            return count>0?true:false;
        }
        
        public void addAutoValue(String value){
            if(value!=null && value.length()>0){
                db.beginTransaction();
                try{
                    String sql = "insert into auto(_id,value) values(null,?)";
                    db.execSQL(sql, new Object[]{value});
                    db.setTransactionSuccessful();
                }finally{
                    db.endTransaction();
                }
            }
        }
        
        public Cursor selectAutoValues(String value){
            String sql = "select _id,value from auto where value like ? limit 10";
            Cursor c = db.rawQuery(sql, new String[]{"%"+value+"%"});
            return c;
        }
        
        
    
        /**
         * 关闭数据连接资源
         */
        public void dbClose(){
            if(null != db){
                db.close();
            }    
        }
    }

    4:AutoCompleteAdater.java

    package com.example.autotest;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.widget.SimpleCursorAdapter;
    
    public class AutoCompleteAdater extends SimpleCursorAdapter{
        private DBManager dbManager = null;
        private Context context;
    
        // 查询字段
        private String value;
        
        @SuppressWarnings("deprecation")
        public AutoCompleteAdater(Context context, int layout, Cursor c,String from, int to) {
           super(context, layout, c, new String[] { from },new int[] { to });
           this.context = context;
           this.value = from;
        }
        
        /**
         * 动态查询数据库
         */
        @Override
        public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
           if (constraint != null) {
               return getDbManager().selectAutoValues((String) constraint);
           } else {
               return null;
           }
        }
        
        /**
         * 这里设置在弹出的提示列表中点击某一项后的返回值,返回值将被显示在文本框中
         */
        @Override
        public CharSequence convertToString(Cursor cursor) {
           return cursor.getString(cursor.getColumnIndex(value));
        }
        
        
        public DBManager getDbManager(){
            return dbManager==null?new DBManager(this.context):dbManager;
        }
    }

    5:MainActivity.java

    package com.example.autotest;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AutoCompleteTextView;
    import android.widget.Button;
    
    public class MainActivity extends Activity {
        private AutoCompleteTextView actValue = null;
        private Button btnClick = null;
        private DBManager dbManager = null;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            actValue = (AutoCompleteTextView) findViewById(R.id.actValue);
            btnClick = (Button)findViewById(R.id.btnClick);
    
            
            AutoCompleteAdater cursorAdapter = new AutoCompleteAdater(
                    this,
                    android.R.layout.simple_dropdown_item_1line,
                    null,
                    "value",
                    android.R.id.text1
                );
            actValue.setAdapter(cursorAdapter);
            
            dbManager = new DBManager(this);
            
            btnClick.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View arg0) {
                    String value = actValue.getText().toString();
                    dbManager.addAutoValue(value);
                }
            });
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if(dbManager!=null){
                dbManager.dbClose();
            }
        }
    }
    java.lang.Object
       ↳ android.view.View
         ↳ android.widget.TextView
           ↳ android.widget.EditText
             ↳ android.widget.AutoCompleteTextView

      可以看出AutoCompleteTextView继承自EditText,所以它实际上也是一个文本编辑框,只是多了一个自动提示补全功能,EditText的所有功能AutoCompleteTextView都能实现,其对EditTextAPI进行了丰富。

  • 相关阅读:
    MyBatis 知识点梳理
    SSH无密码登录的原理及配置
    Maven学习笔记
    阿里Java开发电话面试经历惨败
    Java生成验证码(二)
    Java生成验证码(一)
    Hibernate 知识点梳理
    数据结构线性表顺序表示 (二)
    replace tabs with the proper number of blanks
    数据结构线性表顺序表示 (三)
  • 原文地址:https://www.cnblogs.com/yshyee/p/3579640.html
Copyright © 2020-2023  润新知