import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
-import android.util.Log;
import net.ktnx.mobileledger.model.Data;
import net.ktnx.mobileledger.model.LedgerAccount;
import java.util.ArrayList;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class CommitAccountsTask
extends AsyncTask<CommitAccountsTaskParams, Void, ArrayList<LedgerAccount>> {
protected ArrayList<LedgerAccount> doInBackground(CommitAccountsTaskParams... params) {
try (LockHolder lh = params[0].accountList.lockForWriting()) {
for (int i = 0; i < params[0].accountList.size(); i++ ){
LedgerAccount acc = params[0].accountList.get(i);
- Log.d("CAT", String.format("Setting %s to %s", acc.getName(),
+ debug("CAT", String.format("Setting %s to %s", acc.getName(),
acc.isHiddenByStarToBe() ? "hidden" : "starred"));
db.execSQL("UPDATE accounts SET hidden=? WHERE profile=? AND name=?",
new Object[]{acc.isHiddenByStarToBe() ? 1 : 0, profile, acc.getName()
package net.ktnx.mobileledger.async;
-import android.util.Log;
-
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class DbOpQueue {
static private final BlockingQueue<DbOpItem> queue = new LinkedBlockingQueue<>();
static private DbOpRunner runner;
synchronized static public void init() {
if (runner != null) return;
- Log.d("opQueue", "Starting runner thread");
+ debug("opQueue", "Starting runner thread");
runner = new DbOpRunner(queue);
runner.start();
}
}
public static void add(String sql, Object[] params) {
init();
- Log.d("opQueue", "Adding " + sql);
+ debug("opQueue", "Adding " + sql);
queue.add(new DbOpItem(sql, params));
}
static void add(String sql) {
package net.ktnx.mobileledger.async;
import android.database.sqlite.SQLiteDatabase;
-import android.util.Log;
import net.ktnx.mobileledger.utils.MLDB;
import java.util.concurrent.BlockingQueue;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
class DbOpRunner extends Thread {
private final BlockingQueue<DbOpItem> queue;
public DbOpRunner(BlockingQueue<DbOpItem> queue) {
while (!interrupted()) {
try {
DbOpItem item = queue.take();
- Log.d("opQrunner", "Got "+item.sql);
+ debug("opQrunner", "Got "+item.sql);
SQLiteDatabase db = MLDB.getDatabase();
- Log.d("opQrunner", "Executing "+item.sql);
+ debug("opQrunner", "Executing "+item.sql);
db.execSQL(item.sql, item.params);
}
catch (InterruptedException e) {
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
-import android.util.Log;
import net.ktnx.mobileledger.model.Data;
import net.ktnx.mobileledger.utils.MLDB;
import java.util.HashMap;
import java.util.Map;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class RefreshDescriptionsTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
Map<String, Boolean> unique = new HashMap<>();
- Log.d("descriptions", "Starting refresh");
+ debug("descriptions", "Starting refresh");
SQLiteDatabase db = MLDB.getDatabase();
Data.backgroundTaskStarted();
}
db.execSQL("DELETE from description_history where keep=0");
db.setTransactionSuccessful();
- Log.d("descriptions", "Refresh successful");
+ debug("descriptions", "Refresh successful");
}
finally {
db.endTransaction();
}
finally {
Data.backgroundTaskFinished();
- Log.d("descriptions", "Refresh done");
+ debug("descriptions", "Refresh done");
}
return null;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class RetrieveTransactionsTask
extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
this.contextRef = contextRef;
}
private static void L(String msg) {
- //Log.d("transaction-parser", msg);
+ //debug("transaction-parser", msg);
}
@Override
protected void onProgressUpdate(Progress... values) {
if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
if (orderAccumulator > 30) {
transactionOrder = DetectedTransactionOrder.FILE;
- Log.d("rtt", String.format(
+ debug("rtt", String.format(
"Detected native file order after %d transactions (factor %d)",
processedTransactionCount, orderAccumulator));
progress.setTotal(Data.transactions.size());
}
else if (orderAccumulator < -30) {
transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
- Log.d("rtt", String.format(
+ debug("rtt", String.format(
"Detected reverse chronological order after %d transactions (factor %d)",
processedTransactionCount, orderAccumulator));
}
import java.util.regex.Pattern;
import static android.os.SystemClock.sleep;
+import static net.ktnx.mobileledger.utils.Logger.debug;
public class SendTransactionTask extends AsyncTask<LedgerTransaction, Void, Void> {
private final TaskCallback taskCallback;
http.setDoInput(true);
http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length));
- Log.d("network", "request header: " + http.getRequestProperties().toString());
+ debug("network", "request header: " + http.getRequestProperties().toString());
try (OutputStream req = http.getOutputStream()) {
- Log.d("network", "Request body: " + body);
+ debug("network", "Request body: " + body);
req.write(bodyBytes);
final int responseCode = http.getResponseCode();
- Log.d("network",
+ debug("network",
String.format("Response: %d %s", responseCode, http.getResponseMessage()));
try (InputStream resp = http.getErrorStream()) {
default:
BufferedReader reader = new BufferedReader(new InputStreamReader(resp));
String line = reader.readLine();
- Log.d("network", "Response content: " + line);
+ debug("network", "Response content: " + line);
throw new IOException(
String.format("Error response code %d", responseCode));
}
String body = params.toString();
http.addRequestProperty("Content-Length", String.valueOf(body.length()));
- Log.d("network", "request header: " + http.getRequestProperties().toString());
+ debug("network", "request header: " + http.getRequestProperties().toString());
try (OutputStream req = http.getOutputStream()) {
- Log.d("network", "Request body: " + body);
+ debug("network", "Request body: " + body);
req.write(body.getBytes(StandardCharsets.US_ASCII));
try (InputStream resp = http.getInputStream()) {
- Log.d("update_accounts", String.valueOf(http.getResponseCode()));
+ debug("update_accounts", String.valueOf(http.getResponseCode()));
if (http.getResponseCode() == 303) {
// everything is fine
return true;
Matcher m = reSessionCookie.matcher(cookie);
if (m.matches()) {
session = m.group(1);
- Log.d("network", "new session is " + session);
+ debug("network", "new session is " + session);
}
else {
- Log.d("network", "set-cookie: " + cookie);
+ debug("network", "set-cookie: " + cookie);
Log.w("network",
"Response Set-Cookie headers is not a _SESSION one");
}
"<input type=\"hidden\" name=\"_token\" value=\"([^\"]+)\">");
String line;
while ((line = reader.readLine()) != null) {
- //Log.d("dump", line);
+ //debug("dump", line);
Matcher m = re.matcher(line);
if (m.matches()) {
token = m.group(1);
- Log.d("save-transaction", line);
- Log.d("save-transaction", "Token=" + token);
+ debug("save-transaction", line);
+ debug("save-transaction", "Token=" + token);
return false; // retry
}
}
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
-import android.util.Log;
import net.ktnx.mobileledger.model.Data;
import net.ktnx.mobileledger.model.LedgerAccount;
import java.util.ArrayList;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class UpdateAccountsTask extends AsyncTask<Void, Void, ArrayList<LedgerAccount>> {
protected ArrayList<LedgerAccount> doInBackground(Void... params) {
Data.backgroundTaskStarted();
try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
while (cursor.moveToNext()) {
final String accName = cursor.getString(0);
-// Log.d("accounts",
+// debug("accounts",
// String.format("Read account '%s' from DB [%s]", accName, profileUUID));
LedgerAccount acc = profile.loadAccount(db, accName);
if (acc.isVisible(newList)) newList.add(acc);
return newList;
}
finally {
- Log.d("UAT", "decrementing background task count");
+ debug("UAT", "decrementing background task count");
Data.backgroundTaskFinished();
}
}
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
-import android.util.Log;
import net.ktnx.mobileledger.model.Data;
import net.ktnx.mobileledger.model.LedgerTransaction;
import java.util.ArrayList;
import java.util.Date;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class UpdateTransactionsTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String[] filterAccName) {
final MobileLedgerProfile profile = Data.profile.get();
params = new String[]{profile_uuid, filterAccName[0]};
}
- Log.d("UTT", sql);
+ debug("UTT", sql);
SQLiteDatabase db = MLDB.getDatabase();
String lastDateString = Globals.formatLedgerDate(new Date());
Date lastDate = Globals.parseLedgerDate(lastDateString);
}
newList.add(
new TransactionListItem(new LedgerTransaction(transaction_id), odd));
-// Log.d("UTT", String.format("got transaction %d", transaction_id));
+// debug("UTT", String.format("got transaction %d", transaction_id));
lastDate = date;
lastDateString = dateString;
odd = !odd;
}
Data.transactions.setList(newList);
- Log.d("UTT", "transaction list value updated");
+ debug("UTT", "transaction list value updated");
}
return null;
package net.ktnx.mobileledger.json;
-import android.util.Log;
-
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import java.io.IOException;
import java.io.InputStream;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class AccountListParser {
private final MappingIterator<ParsedLedgerAccount> iter;
if (next.getAname().equalsIgnoreCase("root")) return nextAccount();
- Log.d("accounts", String.format("Got account '%s'", next.getAname()));
+ debug("accounts", String.format("Got account '%s'", next.getAname()));
return next;
}
}
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
-import android.util.Log;
import net.ktnx.mobileledger.utils.LockHolder;
import net.ktnx.mobileledger.utils.MLDB;
import androidx.lifecycle.MutableLiveData;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public final class Data {
public static ObservableList<TransactionListItem> transactions =
new ObservableList<>(new ArrayList<>());
public static MutableLiveData<String> accountFilter = new MutableLiveData<>();
public static void backgroundTaskStarted() {
int cnt = backgroundTaskCount.incrementAndGet();
- Log.d("data", String.format("background task count is %d after incrementing", cnt));
+ debug("data", String.format("background task count is %d after incrementing", cnt));
backgroundTasksRunning.postValue(cnt > 0);
}
public static void backgroundTaskFinished() {
int cnt = backgroundTaskCount.decrementAndGet();
- Log.d("data", String.format("background task count is %d after decrementing", cnt));
+ debug("data", String.format("background task count is %d after decrementing", cnt));
backgroundTasksRunning.postValue(cnt > 0);
}
public static void setCurrentProfile(MobileLedgerProfile newProfile) {
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
-import android.util.Log;
import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
import net.ktnx.mobileledger.json.ParsedPosting;
import java.util.Comparator;
import java.util.Date;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class LedgerTransaction {
private static final String DIGEST_TYPE = "SHA-256";
public final Comparator<LedgerTransactionAccount> comparator =
.rawQuery("SELECT 1 from transactions where data_hash = ?", new String[]{dataHash}))
{
boolean result = c.moveToFirst();
- Log.d("db", String.format("Transaction %d (%s) %s", id, dataHash,
+ debug("db", String.format("Transaction %d (%s) %s", id, dataHash,
result ? "already present" : "not present"));
return result;
}
new String[]{profile, String.valueOf(id)}))
{
while (cAcc.moveToNext()) {
-// Log.d("transactions",
+// debug("transactions",
// String.format("Loaded %d: %s %1.2f %s", id, cAcc.getString(0),
// cAcc.getFloat(1), cAcc.getString(2)));
addAccount(new LedgerTransactionAccount(cAcc.getString(0), cAcc.getFloat(1),
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
-import android.util.Log;
import net.ktnx.mobileledger.async.DbOpQueue;
import net.ktnx.mobileledger.utils.Globals;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public final class MobileLedgerProfile {
private String uuid;
private String name;
SQLiteDatabase db = MLDB.getDatabase();
db.beginTransaction();
try {
-// Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
+// debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
// "url=%s, permit_posting=%s, authEnabled=%s, " +
// "themeId=%d", uuid, name, url,
// permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
});
-// Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
+// debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
}
public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
db.execSQL("replace into account_values(profile, account, " +
item.getCurrency()
});
}
- Log.d("profile", String.format("Transaction %d stored", tr.getId()));
+ debug("profile", String.format("Transaction %d stored", tr.getId()));
}
public String getOption(String name, String default_value) {
SQLiteDatabase db = MLDB.getDatabase();
String result = cursor.getString(0);
if (result == null) {
- Log.d("profile", "returning default value for " + name);
+ debug("profile", "returning default value for " + name);
result = default_value;
}
- else Log.d("profile", String.format("option %s=%s", name, result));
+ else debug("profile", String.format("option %s=%s", name, result));
return result;
}
else return default_value;
}
catch (Exception e) {
- Log.d("db", "returning default value for " + name, e);
+ debug("db", "returning default value for " + name, e);
return default_value;
}
}
long longResult;
String result = getOption(name, "");
if ((result == null) || result.isEmpty()) {
- Log.d("profile", String.format("Returning default value for option %s", name));
+ debug("profile", String.format("Returning default value for option %s", name));
longResult = default_value;
}
else {
try {
longResult = Long.parseLong(result);
- Log.d("profile", String.format("option %s=%s", name, result));
+ debug("profile", String.format("option %s=%s", name, result));
}
catch (Exception e) {
- Log.d("profile", String.format("Returning default value for option %s", name), e);
+ debug("profile", String.format("Returning default value for option %s", name), e);
longResult = default_value;
}
}
return longResult;
}
public void setOption(String name, String value) {
- Log.d("profile", String.format("setting option %s=%s", name, value));
+ debug("profile", String.format("setting option %s=%s", name, value));
DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
new String[]{uuid, name, value});
}
}
public void removeFromDB() {
SQLiteDatabase db = MLDB.getDatabase();
- Log.d("db", String.format("removing profile %s from DB", uuid));
+ debug("db", String.format("removing profile %s from DB", uuid));
db.beginTransaction();
try {
Object[] uuid_param = new Object[]{uuid};
return tr;
}
public int getThemeId() {
-// Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
+// debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
return this.themeId;
}
public void setThemeId(Object o) {
setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
}
public void setThemeId(int themeId) {
-// Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
+// debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
this.themeId = themeId;
}
public void markTransactionsAsNotPresent(SQLiteDatabase db) {
db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
}
public void setLastUpdateStamp() {
- Log.d("db", "Updating transaction value stamp");
+ debug("db", "Updating transaction value stamp");
Date now = new Date();
setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
Data.lastUpdateDate.postValue(now);
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
-import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class HueRing extends View {
private static final int hueStepDegrees = 15;
private Paint ringPaint, initialPaint, currentPaint, markerPaint;
// angleRad is [-𝜋; +𝜋]
float hue = (float) (angleRad / (2 * Math.PI));
if (hue < 0) hue += 1;
- Log.d("TMP",
+ debug("TMP",
String.format("x=%1.3f, y=%1.3f, angle=%1.3frad, hueDegrees=%1.3f", x, y,
angleRad, hue));
setHue(hue);
package net.ktnx.mobileledger.ui;
import android.content.Context;
-import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public abstract class OnSwipeTouchListener implements View.OnTouchListener {
public final GestureDetector gestureDetector;
@Override
public boolean onDown(MotionEvent e) {
- Log.d("sw-l", "onDown");
+ debug("sw-l", "onDown");
return false;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
- Log.d("sw-l", "onFling");
+ debug("sw-l", "onFling");
try {
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
- Log.d("sw-l", "calling onSwipeRight");
+ debug("sw-l", "calling onSwipeRight");
onSwipeRight();
}
else {
- Log.d("sw-l", "calling onSwipeLeft");
+ debug("sw-l", "calling onSwipeLeft");
onSwipeLeft();
}
}
public void onSwipeRight() {}
public void onSwipeLeft() {
- Log.d("sw-l", "LEFT");
+ debug("sw-l", "LEFT");
}
public void onSwipeUp() {}
public void onSwipeDown() {}
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
-import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import androidx.recyclerview.widget.RecyclerView;
import static net.ktnx.mobileledger.ui.activity.SettingsActivity.PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS;
+import static net.ktnx.mobileledger.utils.Logger.debug;
public class AccountSummaryFragment extends MobileLedgerListFragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- Log.d("flow", "AccountSummaryFragment.onCreate()");
+ debug("flow", "AccountSummaryFragment.onCreate()");
setHasOptionsMenu(true);
Data.backgroundTasksRunning.observe(this, this::onBackgroundTaskRunningChanged);
}
public void onAttach(@NotNull Context context) {
super.onAttach(context);
- Log.d("flow", "AccountSummaryFragment.onAttach()");
+ debug("flow", "AccountSummaryFragment.onAttach()");
mActivity = (MainActivity) context;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
- Log.d("flow", "AccountSummaryFragment.onCreateView()");
+ debug("flow", "AccountSummaryFragment.onCreateView()");
return inflater.inflate(R.layout.account_summary_fragment, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
- Log.d("flow", "AccountSummaryFragment.onActivityCreated()");
+ debug("flow", "AccountSummaryFragment.onActivityCreated()");
super.onActivityCreated(savedInstanceState);
modelAdapter = new AccountSummaryAdapter();
// new RecyclerItemListener.RecyclerTouchListener() {
// @Override
// public void onClickItem(View v, int position) {
-// Log.d("value", String.format("item %d clicked", position));
+// debug("value", String.format("item %d clicked", position));
// if (modelAdapter.isSelectionActive()) {
// modelAdapter.selectItem(position);
// }
//
// @Override
// public void onLongClickItem(View v, int position) {
-// Log.d("value", String.format("item %d long-clicked", position));
+// debug("value", String.format("item %d long-clicked", position));
// modelAdapter.startSelection();
// if (optMenu != null) {
// optMenu.findItem(R.id.menu_acc_summary_cancel_selection)
swiper = mActivity.findViewById(R.id.account_swiper);
Colors.themeWatch.observe(this, this::themeChanged);
swiper.setOnRefreshListener(() -> {
- Log.d("ui", "refreshing accounts via swipe");
+ debug("ui", "refreshing accounts via swipe");
mActivity.scheduleTransactionListRetrieval();
});
Data.optShowOnlyStarred.addObserver((o, arg) -> {
boolean newValue = Data.optShowOnlyStarred.get();
- Log.d("pref", String.format("pref change came (%s)", newValue ? "true" : "false"));
+ debug("pref", String.format("pref change came (%s)", newValue ? "true" : "false"));
mShowOnlyStarred.setChecked(newValue);
update_account_table();
});
mShowOnlyStarred.setChecked(Data.optShowOnlyStarred.get());
- Log.d("menu", "Accounts: onCreateOptionsMenu called");
+ debug("menu", "Accounts: onCreateOptionsMenu called");
mShowOnlyStarred.setOnMenuItemClickListener(item -> {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mActivity);
SharedPreferences.Editor editor = pref.edit();
boolean flag = item.isChecked();
editor.putBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, !flag);
- Log.d("pref",
+ debug("pref",
"Setting show only starred accounts pref to " + (flag ? "false" : "true"));
editor.apply();
import android.content.Context;
import android.os.AsyncTask;
-import android.util.Log;
import net.ktnx.mobileledger.async.CommitAccountsTask;
import net.ktnx.mobileledger.async.CommitAccountsTaskParams;
import androidx.lifecycle.ViewModel;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class AccountSummaryViewModel extends ViewModel {
static void commitSelections(Context context) {
CAT task = new CAT();
protected void onPostExecute(ArrayList<LedgerAccount> list) {
super.onPostExecute(list);
if (list != null) {
- Log.d("acc", "setting updated account list");
+ debug("acc", "setting updated account list");
Data.accounts.setList(list);
}
}
protected void onPostExecute(ArrayList<LedgerAccount> list) {
super.onPostExecute(list);
if (list != null) {
- Log.d("acc", "setting new account list");
+ debug("acc", "setting new account list");
Data.accounts.setList(list);
}
}
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public abstract class CrashReportingActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
df.show(getSupportFragmentManager(), "crash_report");
}
});
- Log.d("crash", "Uncaught exception handler set");
+ debug("crash", "Uncaught exception handler set");
}
}
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class MainActivity extends ProfileThemedActivity {
public static final String STATE_CURRENT_PAGE = "current_page";
public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
protected void onStart() {
super.onStart();
- Log.d("flow", "MainActivity.onStart()");
+ debug("flow", "MainActivity.onStart()");
mViewPager.setCurrentItem(mCurrentPage, false);
if (mAccountFilter != null) showTransactionsFragment(mAccountFilter);
else Data.accountFilter.setValue(null);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- Log.d("flow", "MainActivity.onCreate()");
+ debug("flow", "MainActivity.onCreate()");
int profileColor = Data.retrieveCurrentThemeIdFromDb();
Colors.setupTheme(this, profileColor);
Colors.profileThemeId = profileColor;
private void scheduleDataRetrievalIfStale(Date lastUpdate) {
long now = new Date().getTime();
if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
- if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
- else Log.d("db",
+ if (lastUpdate == null) debug("db::", "WEB data never fetched. scheduling a fetch");
+ else debug("db",
String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
lastUpdate.getTime() / 1000f, now / 1000f));
(int) (getResources().getDimension(R.dimen.thumb_row_height) *
Data.profiles.size()));
- Log.d("profiles", "profile list changed");
+ debug("profiles", "profile list changed");
if (arg == null) mProfileListAdapter.notifyDataSetChanged();
else mProfileListAdapter.notifyItemChanged((int) arg);
.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
Data.transactions.clear();
- Log.d("transactions", "requesting list reload");
+ debug("transactions", "requesting list reload");
TransactionListViewModel.scheduleTransactionListReload();
Data.accounts.clear();
int newProfileTheme = (profile == null) ? -1 : profile.getThemeId();
if (newProfileTheme != Colors.profileThemeId) {
- Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
+ debug("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
newProfileTheme));
MainActivity.this.profileThemeChanged();
Colors.profileThemeId = newProfileTheme;
TextView v = findViewById(R.id.transactions_last_update);
if (newValue == null) {
l.setVisibility(View.INVISIBLE);
- Log.d("main", "no last update date :(");
+ debug("main", "no last update date :(");
}
else {
final String text = DateFormat.getDateTimeInstance().format(newValue);
v.setText(text);
l.setVisibility(View.VISIBLE);
- Log.d("main", String.format("Date formatted: %s", text));
+ debug("main", String.format("Date formatted: %s", text));
}
scheduleDataRetrievalIfStale(newValue);
showTransactionsFragment((account == null) ? (String) null : account.getName());
// FragmentTransaction ft = fragmentManager.beginTransaction();
// if (transactionListFragment == null) {
-// Log.d("flow", "MainActivity creating TransactionListFragment");
+// debug("flow", "MainActivity creating TransactionListFragment");
// transactionListFragment = new TransactionListFragment();
// }
// Bundle bundle = new Bundle();
mBackMeansToAccountList = false;
}
else {
- Log.d("fragments", String.format("manager stack: %d",
+ debug("fragments", String.format("manager stack: %d",
fragmentManager.getBackStackEntryCount()));
super.onBackPressed();
final MobileLedgerProfile profile = Data.profile.get();
long last_update = (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
- Log.d("transactions", String.format("Last update = %d", last_update));
+ debug("transactions", String.format("Last update = %d", last_update));
if (last_update == 0) {
Data.lastUpdateDate.postValue(null);
}
retrieveTransactionsTask.execute();
}
public void onStopTransactionRefreshClick(View view) {
- Log.d("interactive", "Cancelling transactions refresh");
+ debug("interactive", "Cancelling transactions refresh");
if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
bTransactionListCancelDownload.setEnabled(false);
}
case R.id.account_row_acc_name:
case R.id.account_expander:
case R.id.account_expander_container:
- Log.d("accounts", "Account expander clicked");
+ debug("accounts", "Account expander clicked");
if (!acc.hasSubAccounts()) return;
boolean wasExpanded = acc.isExpanded();
});
if (wasExpanded) {
- Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
+ debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
arrow.setRotation(0);
animator.rotationBy(180);
try (LockHolder lh = Data.accounts.lockForWriting()) {
for (int i = 0; i < Data.accounts.size(); i++) {
if (acc.isParentOf(Data.accounts.get(i))) {
-// Log.d("accounts", String.format("Found a child '%s' at position %d",
+// debug("accounts", String.format("Found a child '%s' at position %d",
// Data.accounts.get(i).getName(), i));
if (start == -1) {
start = i;
}
else {
if (start != -1) {
-// Log.d("accounts",
+// debug("accounts",
// String.format("Found a non-child '%s' at position %d",
// Data.accounts.get(i).getName(), i));
break;
if (start != -1) {
for (int j = 0; j < count; j++) {
-// Log.d("accounts", String.format("Removing item %d: %s", start + j,
+// debug("accounts", String.format("Removing item %d: %s", start + j,
// Data.accounts.get(start).getName()));
Data.accounts.removeQuietly(start);
}
}
}
else {
- Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
+ debug("accounts", String.format("Expanding account '%s'", acc.getName()));
arrow.setRotation(180);
animator.rotationBy(-180);
List<LedgerAccount> children =
@NotNull
@Override
public Fragment getItem(int position) {
- Log.d("main", String.format("Switching to fragment %d", position));
+ debug("main", String.format("Switching to fragment %d", position));
switch (position) {
case 0:
-// Log.d("flow", "Creating account summary fragment");
+// debug("flow", "Creating account summary fragment");
return mAccountSummaryFragment = new AccountSummaryFragment();
case 1:
return new TransactionListFragment();
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
-import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
/*
* TODO: nicer progress while transaction is submitted
* TODO: reports
tvAmount, null, mProfile);
hookTextChangeListener(tvAccountName);
hookTextChangeListener(tvAmount);
-// Log.d("swipe", "hooked to row "+i);
+// debug("swipe", "hooked to row "+i);
}
}
@Override
saver.execute(tr);
}
catch (ParseException e) {
- Log.d("new-transaction", "Parse error", e);
+ debug("new-transaction", "Parse error", e);
Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
Toast.LENGTH_LONG).show();
tvDate.requestFocus();
if (fab != null) fab.setEnabled(true);
}
catch (Exception e) {
- Log.d("new-transaction", "Unknown error", e);
+ debug("new-transaction", "Unknown error", e);
progress.setVisibility(View.GONE);
toggleAllEditing(true);
}
public boolean simulateCrash(MenuItem item) {
- Log.d("crash", "Will crash intentionally");
+ debug("crash", "Will crash intentionally");
new AsyncCrasher().execute();
return true;
}
@Override
public void afterTextChanged(Editable s) {
-// Log.d("input", "text changed");
+// debug("input", "text changed");
check_transaction_submittable();
}
});
doAddAccountRow(false);
}
- Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
+ debug("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
"amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
"single_empty_with_acc=%s", accounts,
accounts_with_values, amounts_with_accounts, amounts, running_total,
@Override
public void done(String error) {
progress.setVisibility(View.INVISIBLE);
- Log.d("visuals", "hiding progress");
+ debug("visuals", "hiding progress");
if (error == null) resetForm();
else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
}
@Override
public void descriptionSelected(String description) {
- Log.d("descr selected", description);
+ debug("descr selected", description);
if (!inputStateIsInitial()) return;
String accFilter = mProfile.getPreferredAccountsFilter();
sb.append(" ORDER BY date desc limit 1");
final String sql = sb.toString();
- Log.d("descr", sql);
- Log.d("descr", params.toString());
+ debug("descr", sql);
+ debug("descr", params.toString());
try (Cursor c = MLDB.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
if (!c.moveToNext()) return;
package net.ktnx.mobileledger.ui.activity;
import android.os.Bundle;
-import android.util.Log;
import android.view.Menu;
import net.ktnx.mobileledger.R;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
/**
* An activity representing a single Profile detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
if (profile == null) throw new AssertionError(
String.format("Can't get profile " + "(index:%d) from the global list", index));
- Log.d("profiles", String.format("Editing profile %s (%s); hue=%d", profile.getName(),
+ debug("profiles", String.format("Editing profile %s (%s); hue=%d", profile.getName(),
profile.getUuid(), profile.getThemeId()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
- Log.d("profiles", "[activity] Creating profile details options menu");
+ debug("profiles", "[activity] Creating profile details options menu");
if (mFragment != null) mFragment.onCreateOptionsMenu(menu, getMenuInflater());
return true;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
-import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
/**
* A fragment representing a single Profile detail screen.
* a {@link ProfileDetailActivity}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
- Log.d("profiles", "[fragment] Creating profile details options menu");
+ debug("profiles", "[fragment] Creating profile details options menu");
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.profile_details, menu);
final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
builder.setPositiveButton(R.string.Remove, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
- Log.d("profiles",
+ debug("profiles",
String.format("[fragment] removing profile %s", mProfile.getUuid()));
mProfile.removeFromDB();
Data.profiles.remove(mProfile);
if (Data.profile.get().equals(mProfile)) {
- Log.d("profiles", "[fragment] setting current profile to 0");
+ debug("profiles", "[fragment] setting current profile to 0");
Data.setCurrentProfile(Data.profiles.get(0));
}
getActivity().finish();
if (mProfile != null) {
updateProfileFromUI();
-// Log.d("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
+// debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
mProfile.storeInDB();
- Log.d("profiles", "profile stored in DB");
+ debug("profiles", "profile stored in DB");
Data.profiles.triggerItemChangedNotification(mProfile);
rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
- Log.d("profiles", isChecked ? "auth enabled " : "auth disabled");
+ debug("profiles", isChecked ? "auth enabled " : "auth disabled");
authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
if (isChecked) userName.requestFocus();
});
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
-import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class ProfilesRecyclerViewAdapter
extends RecyclerView.Adapter<ProfilesRecyclerViewAdapter.ProfileListViewHolder> {
private final View.OnClickListener mOnClickListener = view -> {
private RecyclerView recyclerView;
private ItemTouchHelper rearrangeHelper;
public ProfilesRecyclerViewAdapter() {
- Log.d("flow", "ProfilesRecyclerViewAdapter.new()");
+ debug("flow", "ProfilesRecyclerViewAdapter.new()");
ItemTouchHelper.Callback cb = new ItemTouchHelper.Callback() {
@Override
MobileLedgerProfile profile = (MobileLedgerProfile) row.getTag();
if (profile == null)
throw new IllegalStateException("Profile row without associated profile");
- Log.d("profiles", "Setting profile to " + profile.getName());
+ debug("profiles", "Setting profile to " + profile.getName());
Data.setCurrentProfile(profile);
});
holder.mTitle.setOnLongClickListener(v -> {
public void onBindViewHolder(@NonNull final ProfileListViewHolder holder, int position) {
final MobileLedgerProfile profile = Data.profiles.get(position);
final MobileLedgerProfile currentProfile = Data.profile.get();
- Log.d("profiles", String.format("pos %d: %s, current: %s", position, profile.getUuid(),
+ debug("profiles", String.format("pos %d: %s, current: %s", position, profile.getUuid(),
(currentProfile == null) ? "<NULL>" : currentProfile.getUuid()));
holder.itemView.setTag(profile);
holder.vTrailer.setVisibility(View.GONE);
LedgerTransaction tr = item.getTransaction();
- // Log.d("transactions", String.format("Filling position %d with %d accounts", position,
+ // debug("transactions", String.format("Filling position %d with %d accounts", position,
// tr.getAccounts().size()));
TransactionLoader loader = new TransactionLoader();
@NonNull
@Override
public TransactionRowHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
-// Log.d("perf", "onCreateViewHolder called");
+// debug("perf", "onCreateViewHolder called");
View row = LayoutInflater.from(parent.getContext())
.inflate(R.layout.transaction_list_row, parent, false);
return new TransactionRowHolder(row);
int rowIndex = 0;
for (LedgerTransactionAccount acc : tr.getAccounts()) {
-// Log.d(c.getAccountName(), acc.getAmount()));
+// debug(c.getAccountName(), acc.getAmount()));
publishProgress(new TransactionLoaderStep(p[0].holder, acc, rowIndex++,
p[0].boldAccountName));
}
LedgerTransactionAccount acc = step.getAccount();
-// Log.d("tmp", String.format("showing acc row %d: %s %1.2f", rowIndex,
+// debug("tmp", String.format("showing acc row %d: %s %1.2f", rowIndex,
// acc.getAccountName(), acc.getAmount()));
String boldAccountName = step.getBoldAccountName();
holder.tableAccounts.getChildCount() - accCount);
}
-// Log.d("transactions",
+// debug("transactions",
// String.format("Position %d fill done", step.getPosition()));
}
}
import android.content.Context;
import android.database.MatrixCursor;
import android.os.Bundle;
-import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import androidx.recyclerview.widget.RecyclerView;
import static android.content.Context.INPUT_METHOD_SERVICE;
+import static net.ktnx.mobileledger.utils.Logger.debug;
public class TransactionListFragment extends MobileLedgerListFragment {
private MenuItem menuTransactionListFilter;
@Override
public void onResume() {
super.onResume();
- Log.d("flow", "TransactionListFragment.onResume()");
+ debug("flow", "TransactionListFragment.onResume()");
}
@Override
public void onStop() {
super.onStop();
- Log.d("flow", "TransactionListFragment.onStop()");
+ debug("flow", "TransactionListFragment.onStop()");
}
@Override
public void onPause() {
super.onPause();
- Log.d("flow", "TransactionListFragment.onPause()");
+ debug("flow", "TransactionListFragment.onPause()");
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
- Log.d("flow", "TransactionListFragment.onActivityCreated called");
+ debug("flow", "TransactionListFragment.onActivityCreated called");
super.onActivityCreated(savedInstanceState);
swiper = mActivity.findViewById(R.id.transaction_swipe);
root.setLayoutManager(llm);
swiper.setOnRefreshListener(() -> {
- Log.d("ui", "refreshing transactions via swipe");
+ debug("ui", "refreshing transactions via swipe");
mActivity.scheduleTransactionListRetrieval();
});
MLDB.hookAutocompletionAdapter(mActivity, accNameFilter, "accounts", "name", true);
accNameFilter.setOnItemClickListener((parent, view, position, id) -> {
-// Log.d("tmp", "direct onItemClick");
+// debug("tmp", "direct onItemClick");
MatrixCursor mc = (MatrixCursor) parent.getItemAtPosition(position);
Data.accountFilter.setValue(mc.getString(1));
Globals.hideSoftKeyboard(mActivity);
import android.app.Activity;
import android.content.res.Resources;
-import android.util.Log;
import android.util.TypedValue;
import net.ktnx.mobileledger.R;
import androidx.lifecycle.MutableLiveData;
import static java.lang.Math.abs;
+import static net.ktnx.mobileledger.utils.Logger.debug;
public class Colors {
public static final int DEFAULT_HUE_DEG = 261;
float l = yellowLightness + (blueLightness - yellowLightness) *
(float) Math.cos(Math.toRadians(Math.abs(180 - y) / 2f));
int result = hslColor(hueDegrees/360f, 0.845f, l);
- Log.d("colors", String.format("getPrimaryColorForHue(%d) = %x", hueDegrees, result));
+ debug("colors", String.format("getPrimaryColorForHue(%d) = %x", hueDegrees, result));
return result;
}
public static void setupTheme(Activity activity) {
break;
default:
activity.setTheme(R.style.AppTheme_NoActionBar);
- Log.d("profiles",
+ debug("profiles",
String.format("Theme hue %d not supported, using the default", themeId));
}
--- /dev/null
+/*
+ * Copyright © 2019 Damyan Ivanov.
+ * This file is part of MoLe.
+ * MoLe is free software: you can distribute it and/or modify it
+ * under the term of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your opinion), any later version.
+ *
+ * MoLe is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License terms for details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+package net.ktnx.mobileledger.utils;
+
+import android.util.Log;
+
+import net.ktnx.mobileledger.BuildConfig;
+
+public final class Logger {
+ public static void debug(String tag, String msg) {
+ if (BuildConfig.DEBUG) Log.d(tag, msg);
+ }
+ public static void debug(String tag, String msg, Throwable e) {
+ if (BuildConfig.DEBUG) Log.d(tag, msg, e);
+ }
+}
import java.io.InputStreamReader;
import java.util.Locale;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public final class MLDB {
public static final String ACCOUNTS_TABLE = "accounts";
public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
return Integer.parseInt(s);
}
catch (Exception e) {
- Log.d("db", "returning default int value of " + name, e);
+ debug("db", "returning default int value of " + name, e);
return default_value;
}
}
return Long.parseLong(s);
}
catch (Exception e) {
- Log.d("db", "returning default long value of " + name, e);
+ debug("db", "returning default long value of " + name, e);
return default_value;
}
}
static public String getOption(String name, String default_value) {
- Log.d("db", "about to fetch option " + name);
+ debug("db", "about to fetch option " + name);
SQLiteDatabase db = getDatabase();
try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
new String[]{NO_PROFILE, name}))
if (result == null) result = default_value;
- Log.d("db", "option " + name + "=" + result);
+ debug("db", "option " + name + "=" + result);
return result;
}
else return default_value;
}
catch (Exception e) {
- Log.d("db", "returning default value for " + name, e);
+ debug("db", "returning default value for " + name, e);
return default_value;
}
}
static public void setOption(String name, String value) {
- Log.d("option", String.format("%s := %s", name, value));
+ debug("option", String.format("%s := %s", name, value));
SQLiteDatabase db = MLDB.getDatabase();
db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
new String[]{NO_PROFILE, name, value});
if (constraint == null) return null;
String str = constraint.toString().toUpperCase();
- Log.d("autocompletion", "Looking for " + str);
+ debug("autocompletion", "Looking for " + str);
String[] col_names = {FontsContract.Columns._ID, field};
MatrixCursor c = new MatrixCursor(col_names);
"ORDER BY 2, 1;", field, field, field, field, table, field);
params = new String[]{str, str, str, str};
}
- Log.d("autocompletion", sql);
+ debug("autocompletion", sql);
SQLiteDatabase db = MLDB.getDatabase();
try (Cursor matches = db.rawQuery(sql, params)) {
while (matches.moveToNext()) {
String match = matches.getString(0);
int order = matches.getInt(1);
- Log.d("autocompletion", String.format("match: %s |%d", match, order));
+ debug("autocompletion", String.format("match: %s |%d", match, order));
c.newRow().add(i++).add(match);
}
}
}
public static synchronized void done() {
if (dbHelper != null) {
- Log.d("db", "Closing DB helper");
+ debug("db", "Closing DB helper");
dbHelper.close();
dbHelper = null;
}
public MobileLedgerDatabase(Application context) {
super(context, DB_NAME, null, LATEST_REVISION);
- Log.d("db", "creating helper instance");
+ debug("db", "creating helper instance");
mContext = context;
super.setWriteAheadLoggingEnabled(true);
}
@Override
public void onCreate(SQLiteDatabase db) {
- Log.d("db", "onCreate called");
+ debug("db", "onCreate called");
applyRevisionFile(db, CREATE_DB_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- Log.d("db", "onUpgrade called");
+ debug("db", "onUpgrade called");
for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
}
throw new SQLException(String.format(Locale.US, "No resource for %s", rev_file));
db.beginTransaction();
try (InputStream res = rm.openRawResource(res_id)) {
- Log.d("db", "Applying " + rev_file);
+ debug("db", "Applying " + rev_file);
InputStreamReader isr = new InputStreamReader(res);
BufferedReader reader = new BufferedReader(isr);
package net.ktnx.mobileledger.utils;
import android.util.Base64;
-import android.util.Log;
import net.ktnx.mobileledger.model.MobileLedgerProfile;
import java.net.URL;
import java.nio.charset.StandardCharsets;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public final class NetworkUtil {
private static final int thirtySeconds = 30000;
public static HttpURLConnection prepareConnection(MobileLedgerProfile profile, String path)
final boolean use_auth = profile.isAuthEnabled();
if (!url.endsWith("/")) url += "/";
url += path;
- Log.d("network", "Connecting to " + url);
+ debug("network", "Connecting to " + url);
HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
if (use_auth) {
final String auth_user = profile.getAuthUserName();
return holder.get();
}
public void set(int newValue) {
-// Log.d("atomic", "set");
+// debug("atomic", "set");
holder.set(newValue);
forceNotify();
}
private void forceNotify() {
setChanged();
-// Log.d("atomic", String.format("notifying %d observers", countObservers()));
+// debug("atomic", String.format("notifying %d observers", countObservers()));
notifyObservers();
}
// public void lazySet(int newValue) {
return result;
}
public int incrementAndGet() {
-// Log.d("atomic", "incrementAndGet");
+// debug("atomic", "incrementAndGet");
int result = holder.incrementAndGet();
forceNotify();
return result;
}
public int decrementAndGet() {
-// Log.d("atomic", "decrementAndGet");
+// debug("atomic", "decrementAndGet");
int result = holder.decrementAndGet();
forceNotify();
return result;
package net.ktnx.mobileledger.utils;
import android.os.Build;
-import android.util.Log;
import org.jetbrains.annotations.NotNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
+import static net.ktnx.mobileledger.utils.Logger.debug;
+
public class ObservableList<T> extends Observable implements List<T> {
private List<T> list;
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
try (LockHolder lh = lockForReading()) {
int index = list.indexOf(item);
if (index == -1) {
- Log.d("ObList", "??? not sending notifications for item not found in the list");
+ debug("ObList", "??? not sending notifications for item not found in the list");
return;
}
- Log.d("ObList", "Notifying item change observers");
+ debug("ObList", "Notifying item change observers");
triggerItemChangedNotification(index);
}
}