它是一个字典搜索,当一个人输入文本时,会弹出建议。 该数据库是一本英语词典。
//Search System
final Context ctx = this;
autoCompleteTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (autoCompleteTextView.getText().length() >= 2) {
DbHandler handler = new DbHandler(getApplicationContext());
final ArrayList<String> Deflist = handler.getSearchList(autoCompleteTextView.getText().toString().trim());
suggestions = Deflist;
handler.close();
if (Deflist != null) {
Search.this.runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter adapter = new ArrayAdapter(ctx, android.R.layout.simple_list_item_1, Deflist);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
}
});
}
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
数据库代码
public void indexDB()
{
try{
getWritableDatabase().execSQL("CREATE INDEX words_index ON entries(word)");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public ArrayList<String> getSearchList(String partWord) {
try {
if (partWord == "") {
return null;
}
ArrayList<Definition> DefList = new ArrayList<>();
ArrayList<String> test = new ArrayList<>();
Definition definition = null;
Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE word LIKE '" + partWord + "%'", null);
try {
if (cursor.moveToFirst()) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
if (!test.contains(word)) {
test.add(word);
}
}
}
} catch (Exception e) {
cursor.close();
}
return test;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
我试图将其编入索引,将限制设置为2或更多以开始搜索,甚至尝试在单独的线程中运行(删除多线程的想法不一致)。有没有办法让它真的很快?
答案 0 :(得分:0)
为了优化对数据库的搜索,我们可以创建一个虚拟全文搜索表,并传递表的数据以搜索到FTS表。
我已经为它实现了一个API。此API还使用预测来获取与搜索查询相关的最接近的单词。
link - https://github.com/gauravat16/Smart-Search
PredictiveSearch search = new PredictiveSearch(getApplicationContext());
ArrayList<String> columns = new ArrayList<>();
columns.add("word");
try {
search.createFTS4Table("learn.db", "entries", columns);
search.ftsRebuilder(); //Use it to rebulid after any change
ArrayList<String> resp1 = search.getSearchList("2"); //Get result w/o stemming
ArrayList<String> resp2 = search.getGuessWord("2"); //Get result with stemming - predictive
} catch (Exception ex) {
ex.printStackTrace();
} finally {
search.close();
}