vendredi 23 octobre 2015

Android - Fastest way to search data in SQLite database

I have an image processing app. My app stores the already processed images in a database. Every time the user opens the app, the app starts to check the database to see what photos have already been processed. With my code this process is taking around 10-20 seconds, which for my needs is a lot of time. The database only has one column, the path of the image. I take the full image list from the phone and then search every item of the list in the database.

My code is as follows:

public static ArrayList<String> getAlreadyProcessedPhotos(Context context, ArrayList<String> photos, SQLiteDatabase db)
{
    ArrayList<String> notAlreadyProcessedPhotos = new ArrayList<>();

    for(String path : photos)
    {
        File imgFile = new File(path);

        if (!Utils.isAlreadyProcessed(context, imgFile, db))
        {
            notAlreadyProcessedPhotos.add(path);
        }
    }

    return notAlreadyProcessedPhotos;
}

public static boolean isAlreadyProcessed(Context context, File imgFile, SQLiteDatabase photosDb) {
    if(photosDb == null || !photosDb.isOpen())
        photosDb = new DatabaseHelper(context).getReadableDatabase();

    String searchQuery = "SELECT * FROM " + DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.PATH_COLUMN + "=?";

    Cursor cursor = photosDb.rawQuery(searchQuery, new String[] {imgFile.getAbsolutePath()});
    boolean result = cursor.moveToFirst();
    cursor.close();

    return result;
}

Aucun commentaire:

Enregistrer un commentaire