]> git.ktnx.net Git - mobile-ledger.git/commitdiff
MLDB: machinery for asynchronous select queries
authorDamyan Ivanov <dam+mobileledger@ktnx.net>
Sun, 3 May 2020 08:55:26 +0000 (11:55 +0300)
committerDamyan Ivanov <dam+mobileledger@ktnx.net>
Sun, 3 May 2020 08:55:26 +0000 (11:55 +0300)
similar to the option setting, but for any kind of statements and with
callbacks

app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java

index 07aea52b34b91a2e425ffda643c77d2a94f57e5f..a449e466917262731d1af8be74b536d9b0679ca2 100644 (file)
@@ -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() {}
     }
 }