英文词典, 以AutoCompleteTextView输入内容到SQLite数据库查找匹配的单词

本示例实现一个英文词典,核心部分就是打开数据库和查询单词,通过openDatabase()方法来实现,另外openDatabase()方法还实现从res\raw目录复制数据库文件到/sdcard/dictionary目录,复制数据实际上先读取,再写入数据的过程

该方法的具体代码如下:

privata SQLiteDatabase openDatabase() {

   try{

       String databaseFilename =  DATABASE_PATH + "/" + DATABASE_FILENAME;

      //  /sdcard/dictionary 目录中没有dictionary.db文件时,将res\raw目录中的数据文件复制到该目录

     if(!(new File(databaseFilename).exists()))   {

           InputStream  is = getResources().openRawResource(R.raw.dictionary);    //定义读取流

           FileOutputStream fos = new FileOutputStream(databaseFilename);

           byte[]  buffer =  new byte[8192];

           int count = is.read(buffer);

           while(count > 0)

           {   fos.write(buffer,0,count); }

          fos.close();

           is.close();

     }

      //  打开数据库

      SQLiteDatabase  database =  SQLiteDatabaset.openOrCreateDatabase(databaseFilename,null);

     return  database;

     }catch(Exception  e){}

    return null;

}

要监视AutoCompleteTextView 组件输入字符的变化,在每输入一个字符时就查询当前输入的字符串开头的英文词典,

为了监视AutoCompleteTextView输入,需要实现TextWatcher接口,并在该接口的afterTextChanged() 中编写如下代码:

public  void  afterTextChanged(Editable s)  {

       Cursor  cursor  =  database.rawQuery("select   english as  _id  from t_words  where  english  like ?",  new String[]{s.toString() + "%"});

        DictionaryAdapter  dictionaryAdapter =  new DictionaryAdapter(this,cursor,true);

       actvWord.setAdapter(dictionaryAdapter);   }

如图

    

具体代码请参见 ch06_dictionary  工程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值