我有大量的字符串,大约15,000,我使用以下代码存储在sqlite数据库中:
void addKey(String key, String value, String table) {
sqliteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_KEY, key); // Contact Name
values.put(KEY_VALUE, value); // Contact Phone
// Inserting Row
db.insert(table, null, values);
db.close(); // Closing database connection
}
然后我使用以下方法搜索该数据库,以便挑选出与我正在寻找的密钥相匹配的任何字符串:
public String searchKeyString(String key, String table){
String rtn = "";
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table;
sqliteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.movetoFirst()) {
do {
Log.d("searchKeyString","searching");
if(cursor.getString(1).equals(key))
rtn = rtn + "," + cursor.getString(2);
} while (cursor.movetoNext());
}
cursor.close();
db.close();
Log.d("searchKeyString","finish search");
return rtn;
}
目标是在用户在保留板上键入时实时执行此操作,因此响应时间是关键,现在它的方式需要一秒钟才能完成搜索.
我考虑最初将所有项目读入数组列表并对可能更快的内容进行排序,但我认为该大小的数组列表可能会导致内存问题.在我的数据库中搜索这些条目的最佳方法是什么?
解决方法:
你可以做几件事……
>将返回值更改为StringBuilder直到结束.
>只使用数据库的可读版本(尽管可能没有太大的区别)
>每次都不要获取数据库的新实例,保持打开直到不再需要它为止
>仅使用SQL查询中的“WHERE”参数查询所需内容.
请参阅以下代码并进行一些更改:
// move this somewhere else in your Activity or such
sqliteDatabase db = this.getReadableDatabase();
public String searchKeyString(String key, String table){
StringBuilder rtn = new StringBuilder();
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table + " WHERE KEY_KEY=?";
Cursor cursor = db.rawQuery(selectQuery, new String[] {key});
// you can change it to
// db.rawQuery("SELECT * FROM "+table+" WHERE KEY_KEY LIKE ?", new String[] {key+"%"});
// if you want to get everything starting with that key value
// looping through all rows and adding to list
if (cursor.movetoFirst()) {
do {
Log.d("searchKeyString","searching");
rtn.append(",").append(cursor.getString(2));
} while (cursor.movetoNext());
}
cursor.close();
Log.d("searchKeyString","finish search");
return rtn.toString();
}
请注意,即使您希望“实时”为用户执行此操作,您仍然需要将其移动到单独的Thread或ASyncTask中,否则您将遇到问题….