2 * Copyright © 2020 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.async;
20 import android.os.AsyncTask;
22 import net.ktnx.mobileledger.model.Data;
23 import net.ktnx.mobileledger.model.TransactionListItem;
24 import net.ktnx.mobileledger.utils.LockHolder;
25 import net.ktnx.mobileledger.utils.Logger;
26 import net.ktnx.mobileledger.utils.SimpleDate;
28 import java.util.Collections;
29 import java.util.Comparator;
30 import java.util.List;
31 import java.util.Locale;
33 public class TransactionDateFinder extends AsyncTask<SimpleDate, Void, Integer> {
35 protected void onPostExecute(Integer pos) {
36 Data.foundTransactionItemIndex.setValue(pos);
39 protected Integer doInBackground(SimpleDate... simpleDates) {
40 SimpleDate date = simpleDates[0];
41 Logger.debug("go-to-date",
42 String.format(Locale.US, "Looking for date %04d-%02d-%02d", date.year, date.month,
44 Logger.debug("go-to-date", String.format(Locale.US, "List contains %d transactions",
45 Data.transactions.size()));
47 try (LockHolder locker = Data.transactions.lockForWriting()) {
48 List<TransactionListItem> transactions = Data.transactions.getList();
49 TransactionListItem target = new TransactionListItem(date, true);
50 int found = Collections.binarySearch(transactions, target,
51 new TransactionListItemComparator());
58 static class TransactionListItemComparator implements Comparator<TransactionListItem> {
60 public int compare(TransactionListItem a, TransactionListItem b) {
61 final SimpleDate aDate = a.getDate();
62 final SimpleDate bDate = b.getDate();
63 int res = aDate.compareTo(bDate);
65 return -res; // transactions are reverse sorted by date
67 if (a.getType() == TransactionListItem.Type.DELIMITER) {
68 if (b.getType() == TransactionListItem.Type.DELIMITER)
74 if (b.getType() == TransactionListItem.Type.DELIMITER)