本示例实现一个英文词典,核心部分就是打开数据库和查询单词,通过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,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 工程
原文链接:https://www.f2er.com/sqlite/202576.html