2 * Copyright © 2019 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.MatrixCursor;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.os.AsyncTask;
26 import android.os.Build;
27 import android.provider.FontsContract;
28 import android.widget.AutoCompleteTextView;
29 import android.widget.FilterQueryProvider;
30 import android.widget.SimpleCursorAdapter;
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 java.util.Locale;
42 import static net.ktnx.mobileledger.utils.Logger.debug;
44 public final class MLDB {
45 public static final String ACCOUNTS_TABLE = "accounts";
46 public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
47 public static final String OPT_LAST_SCRAPE = "last_scrape";
49 public static final String OPT_PROFILE_UUID = "profile_uuid";
50 private static final String NO_PROFILE = "-";
51 @SuppressWarnings("unused")
52 static public int getIntOption(String name, int default_value) {
53 String s = getOption(name, String.valueOf(default_value));
55 return Integer.parseInt(s);
58 debug("db", "returning default int value of " + name, e);
62 @SuppressWarnings("unused")
63 static public long getLongOption(String name, long default_value) {
64 String s = getOption(name, String.valueOf(default_value));
66 return Long.parseLong(s);
69 debug("db", "returning default long value of " + name, e);
73 static public void getOption(String name, String defaultValue, GetOptCallback cb) {
74 AsyncTask<Void, Void, String> t = new AsyncTask<Void, Void, String>() {
76 protected String doInBackground(Void... params) {
77 SQLiteDatabase db = App.getDatabase();
78 try (Cursor cursor = db
79 .rawQuery("select value from options where profile = ? and name=?",
80 new String[]{NO_PROFILE, name}))
82 if (cursor.moveToFirst()) {
83 String result = cursor.getString(0);
85 if (result == null) result = defaultValue;
87 debug("async-db", "option " + name + "=" + result);
90 else return defaultValue;
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);
114 if (result == null) result = default_value;
116 debug("db", "option " + name + "=" + result);
119 else return default_value;
121 catch (Exception e) {
122 debug("db", "returning default value for " + name, e);
123 return default_value;
126 static public void setOption(String name, String value) {
127 debug("option", String.format("%s := %s", name, value));
128 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
129 new String[]{NO_PROFILE, name, value});
131 @SuppressWarnings("unused")
132 static public void setLongOption(String name, long value) {
133 setOption(name, String.valueOf(value));
135 @TargetApi(Build.VERSION_CODES.N)
136 public static void hookAutocompletionAdapter(final Context context,
137 final AutoCompleteTextView view,
138 final String table, final String field) {
139 hookAutocompletionAdapter(context, view, table, field, true, null, null);
141 @TargetApi(Build.VERSION_CODES.N)
142 public static void hookAutocompletionAdapter(final Context context,
143 final AutoCompleteTextView view,
144 final String table, final String field,
145 final boolean profileSpecific,
146 final DescriptionSelectedCallback callback,
147 final MobileLedgerProfile profile) {
148 String[] from = {field};
149 int[] to = {android.R.id.text1};
150 SimpleCursorAdapter adapter =
151 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
153 adapter.setStringConversionColumn(1);
155 FilterQueryProvider provider = constraint -> {
156 if (constraint == null) return null;
158 String str = constraint.toString().toUpperCase();
159 debug("autocompletion", "Looking for " + str);
160 String[] col_names = {FontsContract.Columns._ID, field};
161 MatrixCursor c = new MatrixCursor(col_names);
165 if (profileSpecific) {
166 MobileLedgerProfile p = (profile == null) ? Data.profile.getValue() : profile;
167 if (p == null) throw new AssertionError();
168 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
169 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
170 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 else 9 end " +
172 "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
173 "ORDER BY 2, 1;", field, field, field, field, table, field);
174 params = new String[]{str, str, str, p.getUuid(), str};
177 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
178 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
179 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
180 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
181 "ORDER BY 2, 1;", field, field, field, field, table, field);
182 params = new String[]{str, str, str, str};
184 debug("autocompletion", sql);
185 SQLiteDatabase db = App.getDatabase();
187 try (Cursor matches = db.rawQuery(sql, params)) {
189 while (matches.moveToNext()) {
190 String match = matches.getString(0);
191 int order = matches.getInt(1);
192 debug("autocompletion",
193 String.format(Locale.ENGLISH, "match: %s |%d", match, order));
194 c.newRow().add(i++).add(match);
202 adapter.setFilterQueryProvider(provider);
204 view.setAdapter(adapter);
206 if (callback != null) view.setOnItemClickListener((parent, itemView, position, id) -> {
207 callback.descriptionSelected(String.valueOf(view.getText()));