lundi 9 novembre 2015

How to efficiently query sqlite database multiple times on Android

For my application, I need to query a sqlite database around 40-50 times. I am sure that the code I wrote is very inefficient. Unfortunately, I cannot find many examples online that involves querying the database many times.

String[] entryValArray = new String[indicesList.size()];
DBHelper dbHelper = new DBHelper(MainActivity.context);
SQLiteDatabase db = dbHelper.getReadableDatabase();

for (int i = 0; i < indicesList.size(); i++) {
    int moddedIndex = Integer.parseInt(indicesList.get(i), 16) % DBHelper.numEntries;
    String queryStr = "select * from " + DBHelper.TBL_NAME + " where " + DBHelper.IDStr +
            " = " + Integer.toString(moddedIndex);
    Cursor cursor = db.rawQuery(queryStr, null);
    if (cursor.moveToFirst())
        entryValArray[i] = cursor.getString(1);
    cursor.close();
}

Basically, I am taking a list of strings, converting them to hex values, and then modding the value to get an index into a sqlite database. This is for a password generator application.

Is there a better way to do this, especially regarding creating a cursor and then closing it in every iteration.

Aucun commentaire:

Enregistrer un commentaire