]> git.ktnx.net Git - mobile-ledger-staging.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
faster description pop-up
[mobile-ledger-staging.git] / app / src / main / java / net / ktnx / mobileledger / utils / MLDB.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.utils;
19
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;
29
30 import androidx.annotation.NonNull;
31
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;
37
38 import org.jetbrains.annotations.NonNls;
39
40 import static net.ktnx.mobileledger.utils.Logger.debug;
41
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";
46     @NonNls
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));
52         try {
53             return Integer.parseInt(s);
54         }
55         catch (Exception e) {
56             debug("db", "returning default int value of " + name, e);
57             return default_value;
58         }
59     }
60     @SuppressWarnings("unused")
61     static public long getLongOption(String name, long default_value) {
62         String s = getOption(name, String.valueOf(default_value));
63         try {
64             return Long.parseLong(s);
65         }
66         catch (Exception e) {
67             debug("db", "returning default long value of " + name, e);
68             return default_value;
69         }
70     }
71     static public void getOption(String name, String defaultValue, GetOptCallback cb) {
72         AsyncTask<Void, Void, String> t = new AsyncTask<Void, Void, String>() {
73             @Override
74             protected String doInBackground(Void... params) {
75                 SQLiteDatabase db = App.getDatabase();
76                 try (Cursor cursor = db
77                         .rawQuery("select value from options where profile = ? and name=?",
78                                 new String[]{NO_PROFILE, name}))
79                 {
80                     if (cursor.moveToFirst()) {
81                         String result = cursor.getString(0);
82
83                         if (result == null) result = defaultValue;
84
85                         debug("async-db", "option " + name + "=" + result);
86                         return result;
87                     }
88                     else return defaultValue;
89                 }
90                 catch (Exception e) {
91                     debug("db", "returning default value for " + name, e);
92                     return defaultValue;
93                 }
94             }
95             @Override
96             protected void onPostExecute(String result) {
97                 cb.onResult(result);
98             }
99         };
100
101         t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
102     }
103     static public String getOption(String name, String default_value) {
104         debug("db", "about to fetch option " + name);
105         SQLiteDatabase db = App.getDatabase();
106         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
107                 new String[]{NO_PROFILE, name}))
108         {
109             if (cursor.moveToFirst()) {
110                 String result = cursor.getString(0);
111
112                 if (result == null) result = default_value;
113
114                 debug("db", "option " + name + "=" + result);
115                 return result;
116             }
117             else return default_value;
118         }
119         catch (Exception e) {
120             debug("db", "returning default value for " + name, e);
121             return default_value;
122         }
123     }
124     static public void setOption(String name, String value) {
125         debug("option", String.format("%s := %s", name, value));
126         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
127                 new String[]{NO_PROFILE, name, value});
128     }
129     @SuppressWarnings("unused")
130     static public void setLongOption(String name, long value) {
131         setOption(name, String.valueOf(value));
132     }
133     @TargetApi(Build.VERSION_CODES.N)
134     public static void hookAutocompletionAdapter(final Context context,
135                                                  final AutoCompleteTextView view,
136                                                  final String table, final String field) {
137         hookAutocompletionAdapter(context, view, table, field, true, null, null);
138     }
139     @TargetApi(Build.VERSION_CODES.N)
140     public static void hookAutocompletionAdapter(final Context context,
141                                                  final AutoCompleteTextView view,
142                                                  final String table, final String field,
143                                                  final boolean profileSpecific,
144                                                  final DescriptionSelectedCallback callback,
145                                                  final MobileLedgerProfile profile) {
146         String[] from = {field};
147         int[] to = {android.R.id.text1};
148         SimpleCursorAdapter adapter =
149                 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
150                         from, to, 0);
151         adapter.setStringConversionColumn(1);
152
153         FilterQueryProvider provider = constraint -> {
154             if (constraint == null) return null;
155
156             String str = constraint.toString().toUpperCase();
157             debug("autocompletion", "Looking for " + str);
158
159             String sql;
160             String[] params;
161             if (profileSpecific) {
162                 MobileLedgerProfile p = (profile == null) ? Data.profile.getValue() : profile;
163                 if (p == null) throw new AssertionError();
164                 sql = String.format(
165                         "SELECT rowid as _id, %s, CASE WHEN %s_upper LIKE ?||'%%' THEN 1 " +
166                         "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
167                         "WHEN %s_upper LIKE '%% '||?||'%%' THEN 3 " + "ELSE 9 END " + "FROM %s " +
168                         "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
169                         "ORDER BY 3, %s_upper, 1;", field, field, field, field, table, field,
170                         field);
171                 params = new String[]{str, str, str, p.getUuid(), str};
172             }
173             else {
174                 sql = String.format(
175                         "SELECT rowid as _id, %s, CASE WHEN %s_upper LIKE ?||'%%' THEN 1 " +
176                         "WHEN %s_upper LIKE '%%:'||?||'%%' THEN 2 " +
177                         "WHEN %s_upper LIKE '%% '||?||'%%' THEN 3 " + "ELSE 9 END " + "FROM %s " +
178                         "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 3, %s_upper, 1;", field,
179                         field, field, field, table, field, field);
180                 params = new String[]{str, str, str, str};
181             }
182             debug("autocompletion", sql);
183             SQLiteDatabase db = App.getDatabase();
184
185             return db.rawQuery(sql, params);
186         };
187
188         adapter.setFilterQueryProvider(provider);
189
190         view.setAdapter(adapter);
191
192         if (callback != null) view.setOnItemClickListener((parent, itemView, position, id) -> {
193             callback.descriptionSelected(String.valueOf(view.getText()));
194         });
195     }
196 }
197