簡體   English   中英

Android 上的 SQLite 查詢真的很慢

[英]SQLite query really slow on Android

我有相當大的數據庫,我需要查詢以獲取一些數據並顯示在 Android 上的 ListView 中。 db 大約 5MB,它存儲在 SD 卡上。 它在 2 個表中有 60k 條記錄。 問題是查詢數據庫以獲取來自一個特定列的所有記錄需要非常長的時間 - 就像模擬器和我的手機上的幾分鍾一樣。 我已經嘗試了一切 - 將這些數據存儲在平面文件中,xml - sqlite 是我最后的希望。 這是我用來打開數據庫並查詢它的類:

    public class DataHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "TableName";
    private Context context;
    private SQLiteDatabase db;
    private SQLiteStatement insertStmt;

    public DataHelper(Context context) {
        this.context = context;
        OpenHelper openHelper = new OpenHelper(this.context);
        // this.db = openHelper.getReadableDatabase();

        this.db = SQLiteDatabase.openDatabase(
                Environment.getExternalStorageDirectory()
                        + "/myDB.db", null,
                SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        // this.insertStmt = this.db.compileStatement(INSERT);
    }

    public void deleteAll() {
        this.db.delete(TABLE_NAME, null, null);
    }

    public List<String> selectBrands() {
        List<String> list = new ArrayList<String>();
        Cursor cursor = this.db.query(TABLE_NAME, new String[] { "ColumnName" },
                null, null, null, null, null); 
 }
        if (cursor.moveToFirst()) {
            do {
                if (!(list.contains(cursor.getString(0)))) {
                    list.add(cursor.getString(0));

                }

            } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        return list;
    }

    private static class OpenHelper extends SQLiteOpenHelper {
        OpenHelper(Context context) {
            super(context, null, null, DATABASE_VERSION);

        }

        @Override
        public void onCreate(SQLiteDatabase db) {

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            onCreate(db);
        }
    }

並穿上 ListView 部分:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
        ctxContext = this.getApplicationContext();

        lView = (ListView) findViewById(R.id.ListView01);

        lView.setTextFilterEnabled(true);

        ParseSQLITETask task = new ParseSQLITETask();
        task.execute(null);

    } catch (Exception e) {
        LogErr(e.getMessage());
    }

}

private class ParseSQLITETask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... urls) {
        try {

            DataHelper dHelper = new DataHelper(getApplicationContext());
            list = (ArrayList<String>) dHelper.selectBrands();

        } catch (Exception e) {
            LogErr(e.getMessage());

        }
        return null;

    }

    @Override
    protected void onProgressUpdate(Void... progress) {

    }

    @Override
    protected void onPostExecute(Void result) {
        try {

            lView.setAdapter(new ArrayAdapter<String>(ctxContext,
                    R.layout.list_item, list));
        } catch (Exception e) {
            LogErr(e.getMessage());

        }
    }

}

您正在檢索整個記錄集並將其轉換為ArrayList 不要這樣做。 將 Cursor 傳回並使用適當的適配器(例如SimpleCursorAdapter )。

編輯:您可能還想考慮在該列上創建索引,因為它可能會加快您的檢索時間。

如果沒有測試,我希望你的list.contains會占用很多時間。 您應該能夠使用 SELECT DISTINCT 刪除數據庫庫中的重復項。

編輯:Femi 是正確的,您可能不需要所有記錄的List 光標和/或適配器可能就足夠了。 還要考慮是否可以以任何方式縮小結果范圍(例如 WHERE 子句)。

它與主題沒有直接關系,但我剛剛發現了為什么數據庫查詢非常慢。

就在應用程序冷啟動時,100 毫秒內加載了 20.000 個數據庫條目。 如果在運行的應用程序中重復相同的查詢,則需要 9000 毫秒(9 秒)。

原因是新的 Android Studio數據庫檢查器,它大大減慢了查詢速度。

這是我最終使用的代碼,以防萬一有人遇到類似問題:

public class DataHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "TableName";
    private Context context;
    private SQLiteDatabase db;

    public static final String ColName = "ColumnName";
    public static final String KEY_ID = "_id";

    public DataHelper(Context context) {
        this.context = context;
        OpenHelper openHelper = new OpenHelper(this.context);

        this.db = SQLiteDatabase.openDatabase(
                Environment.getExternalStorageDirectory()
                        + "/myDB.db", null,
                SQLiteDatabase.NO_LOCALIZED_COLLATORS);

    }

    public void deleteAll() {
        this.db.delete(TABLE_NAME, null, null);
    }

    public Cursor selectBrandsCursor() {

        String[] columns = new String[] { ColName, KEY_ID };
        Cursor cursor = this.db.rawQuery("SELECT " + ColName + ", " + KEY_ID
                + " FROM " + TABLE_NAME + " GROUP BY " + ColName + ";", null);

        return cursor;
    }

    private static class OpenHelper extends SQLiteOpenHelper {
        OpenHelper(Context context) {
            super(context, null, null, DATABASE_VERSION);

        }

        @Override
        public void onCreate(SQLiteDatabase db) {

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            onCreate(db);
        }
    }
}

效果非常好,速度更快,免費復制,感謝 Matthew 和 Femi 的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM