搜索存储在sqlite数据库中的字符串的最快方法

Pet*_*ter 3 sqlite android

我有大量的字符串,大约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

    }
Run Code Online (Sandbox Code Playgroud)

然后我使用以下方法搜索该数据库,以便挑选出与我正在寻找的密钥相匹配的任何字符串:

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;
    }
Run Code Online (Sandbox Code Playgroud)

目标是在用户在保留板上键入时实时执行此操作,因此响应时间是关键,现在它的方式需要一秒钟才能完成搜索.

我考虑最初将所有项目读入数组列表并对可能更快的内容进行排序,但我认为该大小的数组列表可能会导致内存问题.在我的数据库中搜索这些条目的最佳方法是什么?

Mat*_*ieu 8

你可以做几件事......

  • 将返回值更改为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();
}
Run Code Online (Sandbox Code Playgroud)

请注意,即使您希望"实时"为用户执行此操作,您仍然需要将其移动到单独的Thread或ASyncTask中,否则您将遇到问题....