From: Damyan Ivanov Date: Sun, 3 May 2020 08:55:26 +0000 (+0300) Subject: MLDB: machinery for asynchronous select queries X-Git-Tag: v0.12.0~27 X-Git-Url: https://git.ktnx.net/?a=commitdiff_plain;h=1c9558f39ac9b1ea8e18a5afeba374e91c95ea2f;p=mobile-ledger.git MLDB: machinery for asynchronous select queries similar to the option setting, but for any kind of statements and with callbacks --- diff --git a/app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java b/app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java index 07aea52b..a449e466 100644 --- a/app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java +++ b/app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java @@ -191,7 +191,41 @@ public final class MLDB { if (callback != null) view.setOnItemClickListener((parent, itemView, position, id) -> { callback.descriptionSelected(String.valueOf(view.getText())); + } + public static void queryInBackground(@NonNull String statement, @NonNull String[] params, + @NonNull CallbackHelper callbackHelper) { + /* All callbacks are called in the new (asynchronous) thread! */ + Thread t = new Thread(() -> { + callbackHelper.onStart(); + try { + SQLiteDatabase db = App.getDatabase(); + + try (Cursor cursor = db.rawQuery(statement, params)) { + boolean gotRow = false; + while (cursor.moveToNext()) { + gotRow = true; + if (!callbackHelper.onRow(cursor)) + break; + } + if (!gotRow) { + callbackHelper.onNoRows(); + } + } + } + catch (Exception e) { + callbackHelper.onException(e); + } + finally { + callbackHelper.onDone(); + } }); + + t.start(); + } + /* MLDB.CallbackHelper -- Abstract class for asynchronous SQL query callbacks */ + @SuppressWarnings("WeakerAccess") + abstract public static class CallbackHelper { + public void onStart() {} } }