英文词典, 以AutoCompleteTextView输入内容到SQLite数据库查找匹
本示例实现一个英文词典,核心部分就是打开数据库和查询单词,通过openDatabase()方法来实现,另外openDatabase()方法还实现从resraw目录复制数据库文件到/sdcard/dictionary目录,复制数据实际上先读取,再写入数据的过程 该方法的具体代码如下: privata SQLiteDatabase openDatabase() { try{ String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; // /sdcard/dictionary 目录中没有dictionary.db文件时,将resraw目录中的数据文件复制到该目录 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,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 工程 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |