效果图,输入a就会调用Sqllite()数据库进行模糊查询,将查询的结果放在list集合中并展示在下面的TexiView()中
//在onCreate()方法的实例化
ex_words.addTextChangedListener(mTextWatcher);
TextWatcher mTextWatcher = new TextWatcher() {
private CharSequence temp;
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
temp = s;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
//这里尤其注意!!!!要对情况进行判空处理,一种是用户输入的值为空,一种是查询的list结果集为空,每一中为空对于setText()都有影响,不然会报空指针错误*****
if (temp.length()>0) {
List<words> list = selectlike(temp.toString());
if(list != null && ! list.isEmpty() ){
tx_fanyiword.setText("提示的内容为"+"\n"+list.toString());
Toast.makeText(getApplicationContext(),"单词提示"+list.toString(),Toast.LENGTH_LONG).show();
}else{
tx_fanyiword.setText("字典里没有该单词哦");
}
// tx_fanyiword.setText(list.toString());
Toast.makeText(getApplicationContext(),temp,Toast.LENGTH_LONG).show();
}else{
tx_fanyiword.setText(" ");
// Toast.makeText(getApplicationContext(),"我是空的",Toast.LENGTH_LONG).show();
}
}
}
模糊查询的方法
public List<words> selectlike(String english){
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
String selectionArgs[] = new String[] { "%" + english + "%" };
String selection = "english LIKE ?" ;//english LIKE ? OR china LIKE ?
Cursor c=db.query("words",null,selection,selectionArgs,null,null,null);
List<words> list=new ArrayList<words>();
if(c != null && c.getCount() >= 1){
while (c.moveToNext()){
//int id = c.getInt(c.getColumnIndex("id"));
words w=new words();
String english1 =c.getString(c.getColumnIndex("english"));
String china1 =c.getString(c.getColumnIndex("china"));
w.setEnglish(english1);
w.setChina(china1);
list.add(w);
return list;
}
}else{
Toast.makeText(getApplicationContext(),"没有匹配的数据",Toast.LENGTH_SHORT).show();
}
db.close();
return null;
}