2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.utils;
20 import android.annotation.TargetApi;
21 import android.content.Context;
22 import android.database.Cursor;
23 import android.database.sqlite.SQLiteDatabase;
24 import android.os.AsyncTask;
25 import android.os.Build;
26 import android.widget.AutoCompleteTextView;
27 import android.widget.FilterQueryProvider;
28 import android.widget.SimpleCursorAdapter;
30 import androidx.annotation.NonNull;
32 import net.ktnx.mobileledger.App;
33 import net.ktnx.mobileledger.async.DbOpQueue;
34 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
35 import net.ktnx.mobileledger.model.Data;
36 import net.ktnx.mobileledger.model.MobileLedgerProfile;
38 import org.jetbrains.annotations.NonNls;
40 import static net.ktnx.mobileledger.utils.Logger.debug;
42 public final class MLDB {
43 public static final String ACCOUNTS_TABLE = "accounts";
44 public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
45 public static final String OPT_LAST_SCRAPE = "last_scrape";
47 public static final String OPT_PROFILE_UUID = "profile_uuid";
48 private static final String NO_PROFILE = "-";
49 @SuppressWarnings("unused")
50 static public int getIntOption(String name, int default_value) {
51 String s = getOption(name, String.valueOf(default_value));
53 return Integer.parseInt(s);
56 debug("db", "returning default int value of " + name, e);
60 @SuppressWarnings("unused")
61 static public long getLongOption(String name, long default_value) {
62 String s = getOption(name, String.valueOf(default_value));
64 return Long.parseLong(s);
67 debug("db", "returning default long value of " + name, e);
71 static public void getOption(String name, String defaultValue, GetOptCallback cb) {
72 AsyncTask<Void, Void, String> t = new AsyncTask<Void, Void, String>() {
74 protected String doInBackground(Void... params) {
75 SQLiteDatabase db = App.getDatabase();
76 try (Cursor cursor = db.rawQuery(
77 "select value from options where profile=? and name=?",
78 new String[]{NO_PROFILE, name}))
80 if (cursor.moveToFirst()) {
81 String result = cursor.getString(0);
84 result = defaultValue;
86 debug("async-db", "option " + name + "=" + result);
93 debug("db", "returning default value for " + name, e);
98 protected void onPostExecute(String result) {
103 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
105 static public String getOption(String name, String default_value) {
106 debug("db", "about to fetch option " + name);
107 SQLiteDatabase db = App.getDatabase();
108 try (Cursor cursor = db.rawQuery("select value from options where profile=? and name=?",
109 new String[]{NO_PROFILE, name}))
111 if (cursor.moveToFirst()) {
112 String result = cursor.getString(0);
115 result = default_value;
117 debug("db", "option " + name + "=" + result);
121 return default_value;
123 catch (Exception e) {
124 debug("db", "returning default value for " + name, e);
125 return default_value;
128 static public void setOption(String name, String value) {
129 debug("option", String.format("%s := %s", name, value));
130 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
131 new String[]{NO_PROFILE, name, value});
133 @SuppressWarnings("unused")
134 static public void setLongOption(String name, long value) {
135 setOption(name, String.valueOf(value));
137 @TargetApi(Build.VERSION_CODES.N)
138 public static void hookAutocompletionAdapter(final Context context,
139 final AutoCompleteTextView view,
140 final String table, final String field) {
141 hookAutocompletionAdapter(context, view, table, field, true, null, null);
143 @TargetApi(Build.VERSION_CODES.N)
144 public static void hookAutocompletionAdapter(final Context context,
145 final AutoCompleteTextView view,
146 final String table, final String field,
147 final boolean profileSpecific,
148 final DescriptionSelectedCallback callback,
149 final MobileLedgerProfile profile) {
150 String[] from = {field};
151 int[] to = {android.R.id.text1};
152 SimpleCursorAdapter adapter =
153 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
155 adapter.setStringConversionColumn(1);
157 FilterQueryProvider provider = constraint -> {
158 if (constraint == null)
161 String str = constraint.toString()
163 debug("autocompletion", "Looking for " + str);
167 if (profileSpecific) {
168 MobileLedgerProfile p = (profile == null) ? Data.getProfile() : profile;
170 "SELECT rowid as _id, %s, CASE WHEN %s_upper LIKE ?||'%%' THEN 1 " +
171 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
172 "WHEN %s_upper LIKE '%% '||?||'%%' THEN 3 " + "ELSE 9 END " + "FROM %s " +
173 "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
174 "ORDER BY 3, %s_upper, 1;", field, field, field, field, table, field,
176 params = new String[]{str, str, str, p.getUuid(), str};
180 "SELECT rowid as _id, %s, CASE WHEN %s_upper LIKE ?||'%%' THEN 1 " +
181 "WHEN %s_upper LIKE '%%:'||?||'%%' THEN 2 " +
182 "WHEN %s_upper LIKE '%% '||?||'%%' THEN 3 " + "ELSE 9 END " + "FROM %s " +
183 "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 3, %s_upper, 1;", field,
184 field, field, field, table, field, field);
185 params = new String[]{str, str, str, str};
187 debug("autocompletion", sql);
188 SQLiteDatabase db = App.getDatabase();
190 return db.rawQuery(sql, params);
193 adapter.setFilterQueryProvider(provider);
195 view.setAdapter(adapter);
197 if (callback != null)
198 view.setOnItemClickListener(
199 (parent, itemView, position, id) -> callback.descriptionSelected(
200 String.valueOf(view.getText())));
202 public static void queryInBackground(@NonNull String statement, String[] params,
203 @NonNull final CallbackHelper callbackHelper) {
204 /* All callbacks are called in the new (asynchronous) thread! */
205 Thread t = new Thread(() -> {
206 callbackHelper.onStart();
208 SQLiteDatabase db = App.getDatabase();
210 try (Cursor cursor = db.rawQuery(statement, params)) {
211 boolean gotRow = false;
212 while (cursor.moveToNext()) {
214 if (!callbackHelper.onRow(cursor))
218 callbackHelper.onNoRows();
222 catch (Exception e) {
223 callbackHelper.onException(e);
226 callbackHelper.onDone();
232 /* MLDB.CallbackHelper -- Abstract class for asynchronous SQL query callbacks */
233 @SuppressWarnings("WeakerAccess")
234 abstract public static class CallbackHelper {
235 public void onStart() {}
236 public abstract boolean onRow(@NonNull Cursor cursor);
237 public void onNoRows() {}
238 public void onException(Exception exception) {
239 Logger.debug("MLDB", "Exception in asynchronous SQL", exception);
241 public void onDone() {}