From 11970004f081b401f0157692ee1498d8049f1654 Mon Sep 17 00:00:00 2001 From: Sylvia van Os Date: Sun, 7 Nov 2021 15:38:55 +0100 Subject: [PATCH] Android Studio reformat --- .../protect/card_locker/AboutActivity.java | 31 ++-- .../card_locker/BarcodeSelectorActivity.java | 1 - .../card_locker/BaseCursorAdapter.java | 47 ++--- .../card_locker/CardShortcutConfigure.java | 3 +- .../protect/card_locker/CatimaBarcode.java | 50 +++--- .../java/protect/card_locker/DBHelper.java | 163 +++++++----------- .../protect/card_locker/FormatException.java | 9 +- .../main/java/protect/card_locker/Group.java | 14 +- .../card_locker/GroupCursorAdapter.java | 21 +-- .../card_locker/ImportExportActivity.java | 1 - .../protect/card_locker/ImportURIHelper.java | 30 ++-- .../protect/card_locker/LetterBitmap.java | 48 ++---- .../java/protect/card_locker/LoyaltyCard.java | 20 +-- .../card_locker/LoyaltyCardCursorAdapter.java | 47 +++-- .../card_locker/LoyaltyCardEditActivity.java | 110 ++++++------ .../LoyaltyCardLockerApplication.java | 1 - .../card_locker/LoyaltyCardViewActivity.java | 11 +- .../protect/card_locker/MainActivity.java | 135 +++++---------- .../card_locker/ManageGroupActivity.java | 67 ++++--- .../card_locker/ManageGroupCursorAdapter.java | 37 ++-- .../card_locker/ManageGroupsActivity.java | 22 +-- .../protect/card_locker/ScanActivity.java | 17 +- .../protect/card_locker/ShortcutHelper.java | 38 ++-- .../card_locker/SimpleTextWatcher.java | 9 +- .../main/java/protect/card_locker/Utils.java | 23 ++- .../card_locker/async/CompatCallable.java | 1 + .../card_locker/async/TaskHandler.java | 9 +- .../card_locker/importexport/CSVHelpers.java | 45 ++--- .../importexport/CatimaExporter.java | 42 ++--- .../importexport/CatimaImporter.java | 72 +++----- .../card_locker/importexport/DataFormat.java | 6 +- .../card_locker/importexport/Exporter.java | 6 +- .../importexport/FidmeImporter.java | 5 +- .../importexport/ImportExportResult.java | 6 +- .../card_locker/importexport/Importer.java | 4 +- .../importexport/MultiFormatExporter.java | 31 ++-- .../importexport/MultiFormatImporter.java | 29 +--- .../importexport/StocardImporter.java | 25 ++- .../importexport/VoucherVaultImporter.java | 5 +- .../card_locker/preferences/Settings.java | 64 +++---- .../preferences/SettingsActivity.java | 18 +- 41 files changed, 518 insertions(+), 805 deletions(-) diff --git a/app/src/main/java/protect/card_locker/AboutActivity.java b/app/src/main/java/protect/card_locker/AboutActivity.java index 739d5ef24..2a56836f0 100644 --- a/app/src/main/java/protect/card_locker/AboutActivity.java +++ b/app/src/main/java/protect/card_locker/AboutActivity.java @@ -24,22 +24,19 @@ import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.core.text.HtmlCompat; -public class AboutActivity extends CatimaAppCompatActivity implements View.OnClickListener -{ +public class AboutActivity extends CatimaAppCompatActivity implements View.OnClickListener { private static final String TAG = "Catima"; ConstraintLayout version_history, translate, license, repo, privacy, error, credits, rate; @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.about); setContentView(R.layout.about_activity); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); - if(actionBar != null) - { + if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } @@ -59,7 +56,8 @@ public class AboutActivity extends CatimaAppCompatActivity implements View.OnCli contributors.append("
"); contributors.append(tmp); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } final List USED_LIBRARIES = new ArrayList<>(); USED_LIBRARIES.add(new ThirdPartyInfo("Color Picker", "https://github.com/jaredrummler/ColorPicker", "Apache 2.0")); @@ -73,14 +71,12 @@ public class AboutActivity extends CatimaAppCompatActivity implements View.OnCli USED_ASSETS.add(new ThirdPartyInfo("Android icons", "https://fonts.google.com/icons?selected=Material+Icons", "Apache 2.0")); StringBuilder libs = new StringBuilder().append("
"); - for (ThirdPartyInfo entry : USED_LIBRARIES) - { + for (ThirdPartyInfo entry : USED_LIBRARIES) { libs.append("
").append(entry.name()).append(" (").append(entry.license()).append(")"); } StringBuilder resources = new StringBuilder().append("
"); - for (ThirdPartyInfo entry : USED_ASSETS) - { + for (ThirdPartyInfo entry : USED_ASSETS) { resources.append("
").append(entry.name()).append(" (").append(entry.license()).append(")"); } @@ -88,13 +84,10 @@ public class AboutActivity extends CatimaAppCompatActivity implements View.OnCli int year = Calendar.getInstance().get(Calendar.YEAR); String version = "?"; - try - { + try { PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0); version = pi.versionName; - } - catch (PackageManager.NameNotFoundException e) - { + } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Package name not found", e); } @@ -134,13 +127,13 @@ public class AboutActivity extends CatimaAppCompatActivity implements View.OnCli credits.setOnClickListener(view -> new AlertDialog.Builder(this) .setTitle(R.string.credits) .setMessage(contributorInfo.toString()) - .setPositiveButton(R.string.ok, (dialogInterface, i) -> {}) + .setPositiveButton(R.string.ok, (dialogInterface, i) -> { + }) .show()); } @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); diff --git a/app/src/main/java/protect/card_locker/BarcodeSelectorActivity.java b/app/src/main/java/protect/card_locker/BarcodeSelectorActivity.java index 0251e9230..6457f3b54 100644 --- a/app/src/main/java/protect/card_locker/BarcodeSelectorActivity.java +++ b/app/src/main/java/protect/card_locker/BarcodeSelectorActivity.java @@ -22,7 +22,6 @@ import java.util.Map; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; - import protect.card_locker.async.TaskHandler; /** diff --git a/app/src/main/java/protect/card_locker/BaseCursorAdapter.java b/app/src/main/java/protect/card_locker/BaseCursorAdapter.java index a20041e1d..7c9d77899 100644 --- a/app/src/main/java/protect/card_locker/BaseCursorAdapter.java +++ b/app/src/main/java/protect/card_locker/BaseCursorAdapter.java @@ -4,14 +4,12 @@ import android.database.Cursor; import androidx.recyclerview.widget.RecyclerView; -public abstract class BaseCursorAdapter extends RecyclerView.Adapter -{ +public abstract class BaseCursorAdapter extends RecyclerView.Adapter { private Cursor mCursor; private boolean mDataValid; private int mRowIDColumn; - public BaseCursorAdapter(Cursor inputCursor) - { + public BaseCursorAdapter(Cursor inputCursor) { setHasStableIds(true); swapCursor(inputCursor); } @@ -19,15 +17,12 @@ public abstract class BaseCursorAdapter exten public abstract void onBindViewHolder(V inputHolder, Cursor inputCursor); @Override - public void onBindViewHolder(V inputHolder, int inputPosition) - { - if (!mDataValid) - { + public void onBindViewHolder(V inputHolder, int inputPosition) { + if (!mDataValid) { throw new IllegalStateException("Cannot bind view holder when cursor is in invalid state."); } - if (!mCursor.moveToPosition(inputPosition)) - { + if (!mCursor.moveToPosition(inputPosition)) { throw new IllegalStateException("Could not move cursor to position " + inputPosition + " when trying to bind view holder"); } @@ -35,49 +30,37 @@ public abstract class BaseCursorAdapter exten } @Override - public int getItemCount() - { - if (mDataValid) - { + public int getItemCount() { + if (mDataValid) { return mCursor.getCount(); - } - else - { + } else { return 0; } } @Override - public long getItemId(int inputPosition) - { - if (!mDataValid) - { + public long getItemId(int inputPosition) { + if (!mDataValid) { throw new IllegalStateException("Cannot lookup item id when cursor is in invalid state."); } - if (!mCursor.moveToPosition(inputPosition)) - { + if (!mCursor.moveToPosition(inputPosition)) { throw new IllegalStateException("Could not move cursor to position " + inputPosition + " when trying to get an item id"); } return mCursor.getLong(mRowIDColumn); } - public void swapCursor(Cursor inputCursor) - { - if (inputCursor == mCursor) - { + public void swapCursor(Cursor inputCursor) { + if (inputCursor == mCursor) { return; } - if (inputCursor != null) - { + if (inputCursor != null) { mCursor = inputCursor; mDataValid = true; notifyDataSetChanged(); - } - else - { + } else { notifyItemRangeRemoved(0, getItemCount()); mCursor = null; mRowIDColumn = -1; diff --git a/app/src/main/java/protect/card_locker/CardShortcutConfigure.java b/app/src/main/java/protect/card_locker/CardShortcutConfigure.java index 1b8d771a5..be9cc84d5 100644 --- a/app/src/main/java/protect/card_locker/CardShortcutConfigure.java +++ b/app/src/main/java/protect/card_locker/CardShortcutConfigure.java @@ -19,8 +19,7 @@ import androidx.recyclerview.widget.RecyclerView; /** * The configuration screen for creating a shortcut. */ -public class CardShortcutConfigure extends AppCompatActivity implements LoyaltyCardCursorAdapter.CardAdapterListener -{ +public class CardShortcutConfigure extends AppCompatActivity implements LoyaltyCardCursorAdapter.CardAdapterListener { static final String TAG = "Catima"; final DBHelper mDb = new DBHelper(this); diff --git a/app/src/main/java/protect/card_locker/CatimaBarcode.java b/app/src/main/java/protect/card_locker/CatimaBarcode.java index 2b295f5c5..c402f7991 100644 --- a/app/src/main/java/protect/card_locker/CatimaBarcode.java +++ b/app/src/main/java/protect/card_locker/CatimaBarcode.java @@ -8,33 +8,33 @@ import java.util.List; public class CatimaBarcode { public static final List barcodeFormats = Collections.unmodifiableList(Arrays.asList( - BarcodeFormat.AZTEC, - BarcodeFormat.CODE_39, - BarcodeFormat.CODE_128, - BarcodeFormat.CODABAR, - BarcodeFormat.DATA_MATRIX, - BarcodeFormat.EAN_8, - BarcodeFormat.EAN_13, - BarcodeFormat.ITF, - BarcodeFormat.PDF_417, - BarcodeFormat.QR_CODE, - BarcodeFormat.UPC_A, - BarcodeFormat.UPC_E + BarcodeFormat.AZTEC, + BarcodeFormat.CODE_39, + BarcodeFormat.CODE_128, + BarcodeFormat.CODABAR, + BarcodeFormat.DATA_MATRIX, + BarcodeFormat.EAN_8, + BarcodeFormat.EAN_13, + BarcodeFormat.ITF, + BarcodeFormat.PDF_417, + BarcodeFormat.QR_CODE, + BarcodeFormat.UPC_A, + BarcodeFormat.UPC_E )); public static final List barcodePrettyNames = Collections.unmodifiableList(Arrays.asList( - "Aztec", - "Code 39", - "Code 128", - "Codabar", - "Data Matrix", - "EAN 8", - "EAN 13", - "ITF", - "PDF 417", - "QR Code", - "UPC A", - "UPC E" + "Aztec", + "Code 39", + "Code 128", + "Codabar", + "Data Matrix", + "EAN 8", + "EAN 13", + "ITF", + "PDF 417", + "QR Code", + "UPC A", + "UPC E" )); private final BarcodeFormat mBarcodeFormat; @@ -63,7 +63,7 @@ public class CatimaBarcode { return barcodeFormats.contains(mBarcodeFormat); } - public boolean isSquare(){ + public boolean isSquare() { return mBarcodeFormat == BarcodeFormat.AZTEC || mBarcodeFormat == BarcodeFormat.DATA_MATRIX || mBarcodeFormat == BarcodeFormat.MAXICODE diff --git a/app/src/main/java/protect/card_locker/DBHelper.java b/app/src/main/java/protect/card_locker/DBHelper.java index 505f3be52..eba29d9f1 100644 --- a/app/src/main/java/protect/card_locker/DBHelper.java +++ b/app/src/main/java/protect/card_locker/DBHelper.java @@ -18,21 +18,18 @@ import java.util.Currency; import java.util.Date; import java.util.List; -public class DBHelper extends SQLiteOpenHelper -{ +public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "Catima.db"; public static final int ORIGINAL_DATABASE_VERSION = 1; public static final int DATABASE_VERSION = 14; - public static class LoyaltyCardDbGroups - { + public static class LoyaltyCardDbGroups { public static final String TABLE = "groups"; public static final String ID = "_id"; public static final String ORDER = "orderId"; } - public static class LoyaltyCardDbIds - { + public static class LoyaltyCardDbIds { public static final String TABLE = "cards"; public static final String ID = "_id"; public static final String STORE = "store"; @@ -50,15 +47,13 @@ public class DBHelper extends SQLiteOpenHelper public static final String ZOOM_LEVEL = "zoomlevel"; } - public static class LoyaltyCardDbIdsGroups - { + public static class LoyaltyCardDbIdsGroups { public static final String TABLE = "cardsGroups"; public static final String cardID = "cardId"; public static final String groupID = "groupId"; } - public static class LoyaltyCardDbFTS - { + public static class LoyaltyCardDbFTS { public static final String TABLE = "fts"; public static final String ID = "rowid"; // This should NEVER be changed public static final String STORE = "store"; @@ -78,16 +73,14 @@ public class DBHelper extends SQLiteOpenHelper private Context mContext; - public DBHelper(Context context) - { + public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } @Override - public void onCreate(SQLiteDatabase db) - { + public void onCreate(SQLiteDatabase db) { // create table for card groups db.execSQL("CREATE TABLE " + LoyaltyCardDbGroups.TABLE + "(" + LoyaltyCardDbGroups.ID + " TEXT primary key not null," + @@ -107,14 +100,14 @@ public class DBHelper extends SQLiteOpenHelper LoyaltyCardDbIds.BARCODE_ID + " TEXT," + LoyaltyCardDbIds.BARCODE_TYPE + " TEXT," + LoyaltyCardDbIds.STAR_STATUS + " INTEGER DEFAULT '0'," + - LoyaltyCardDbIds.LAST_USED + " INTEGER DEFAULT '0', "+ + LoyaltyCardDbIds.LAST_USED + " INTEGER DEFAULT '0', " + LoyaltyCardDbIds.ZOOM_LEVEL + " INTEGER DEFAULT '100' )"); // create associative table for cards in groups db.execSQL("CREATE TABLE " + LoyaltyCardDbIdsGroups.TABLE + "(" + LoyaltyCardDbIdsGroups.cardID + " INTEGER," + LoyaltyCardDbIdsGroups.groupID + " TEXT," + - "primary key (" + LoyaltyCardDbIdsGroups.cardID + "," + LoyaltyCardDbIdsGroups.groupID +"))"); + "primary key (" + LoyaltyCardDbIdsGroups.cardID + "," + LoyaltyCardDbIdsGroups.groupID + "))"); // create FTS search table db.execSQL("CREATE VIRTUAL TABLE " + LoyaltyCardDbFTS.TABLE + " USING fts4(" + @@ -124,67 +117,57 @@ public class DBHelper extends SQLiteOpenHelper @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) - { - if(oldVersion < 2 && newVersion >= 2) - { + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + if (oldVersion < 2 && newVersion >= 2) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.NOTE + " TEXT not null default ''"); } - if(oldVersion < 3 && newVersion >= 3) - { + if (oldVersion < 3 && newVersion >= 3) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.HEADER_COLOR + " INTEGER"); db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.HEADER_TEXT_COLOR + " INTEGER"); } - if(oldVersion < 4 && newVersion >= 4) - { + if (oldVersion < 4 && newVersion >= 4) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.STAR_STATUS + " INTEGER DEFAULT '0'"); } - if(oldVersion < 5 && newVersion >= 5) - { + if (oldVersion < 5 && newVersion >= 5) { db.execSQL("CREATE TABLE " + LoyaltyCardDbGroups.TABLE + "(" + LoyaltyCardDbGroups.ID + " TEXT primary key not null)"); db.execSQL("CREATE TABLE " + LoyaltyCardDbIdsGroups.TABLE + "(" + LoyaltyCardDbIdsGroups.cardID + " INTEGER," + LoyaltyCardDbIdsGroups.groupID + " TEXT," + - "primary key (" + LoyaltyCardDbIdsGroups.cardID + "," + LoyaltyCardDbIdsGroups.groupID +"))"); + "primary key (" + LoyaltyCardDbIdsGroups.cardID + "," + LoyaltyCardDbIdsGroups.groupID + "))"); } - if(oldVersion < 6 && newVersion >= 6) - { + if (oldVersion < 6 && newVersion >= 6) { db.execSQL("ALTER TABLE " + LoyaltyCardDbGroups.TABLE + " ADD COLUMN " + LoyaltyCardDbGroups.ORDER + " INTEGER DEFAULT '0'"); } - if(oldVersion < 7 && newVersion >= 7) - { + if (oldVersion < 7 && newVersion >= 7) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.EXPIRY + " INTEGER"); } - if(oldVersion < 8 && newVersion >= 8) - { + if (oldVersion < 8 && newVersion >= 8) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.BALANCE + " TEXT not null DEFAULT '0'"); db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.BALANCE_TYPE + " TEXT"); } - if(oldVersion < 9 && newVersion >= 9) - { + if (oldVersion < 9 && newVersion >= 9) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.BARCODE_ID + " TEXT"); } - if(oldVersion < 10 && newVersion >= 10) - { + if (oldVersion < 10 && newVersion >= 10) { // SQLite doesn't support modify column // So we need to create a temp column to make barcode type nullable // Let's drop header text colour too while we're at it @@ -277,14 +260,12 @@ public class DBHelper extends SQLiteOpenHelper db.endTransaction(); } - if(oldVersion < 11 && newVersion >= 11) - { + if (oldVersion < 11 && newVersion >= 11) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.LAST_USED + " INTEGER DEFAULT '0'"); } - if(oldVersion < 12 && newVersion >= 12) - { + if (oldVersion < 12 && newVersion >= 12) { db.execSQL("CREATE VIRTUAL TABLE " + LoyaltyCardDbFTS.TABLE + " USING fts4(" + LoyaltyCardDbFTS.STORE + ", " + LoyaltyCardDbFTS.NOTE + ", " + "tokenize=unicode61);"); @@ -301,8 +282,7 @@ public class DBHelper extends SQLiteOpenHelper } } - if(oldVersion < 13 && newVersion >= 13) - { + if (oldVersion < 13 && newVersion >= 13) { db.execSQL("DELETE FROM " + LoyaltyCardDbFTS.TABLE + ";"); Cursor cursor = db.rawQuery("SELECT * FROM " + LoyaltyCardDbIds.TABLE + ";", null, null); @@ -323,7 +303,7 @@ public class DBHelper extends SQLiteOpenHelper cursor.close(); } - if(oldVersion < 14 && newVersion >= 14){ + if (oldVersion < 14 && newVersion >= 14) { db.execSQL("ALTER TABLE " + LoyaltyCardDbIds.TABLE + " ADD COLUMN " + LoyaltyCardDbIds.ZOOM_LEVEL + " INTEGER DEFAULT '100' "); } @@ -374,8 +354,7 @@ public class DBHelper extends SQLiteOpenHelper final BigDecimal balance, final Currency balanceType, final String cardId, final String barcodeId, final CatimaBarcode barcodeType, final Integer headerColor, - final int starStatus, final Long lastUsed) - { + final int starStatus, final Long lastUsed) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); @@ -408,8 +387,7 @@ public class DBHelper extends SQLiteOpenHelper final Currency balanceType, final String cardId, final String barcodeId, final CatimaBarcode barcodeType, final Integer headerColor, final int starStatus, - final Long lastUsed) - { + final Long lastUsed) { db.beginTransaction(); // Card @@ -441,8 +419,7 @@ public class DBHelper extends SQLiteOpenHelper final Currency balanceType, final String cardId, final String barcodeId, final CatimaBarcode barcodeType, final Integer headerColor, final int starStatus, - final Long lastUsed) - { + final Long lastUsed) { db.beginTransaction(); // Card @@ -474,8 +451,7 @@ public class DBHelper extends SQLiteOpenHelper final Date expiry, final BigDecimal balance, final Currency balanceType, final String cardId, final String barcodeId, final CatimaBarcode barcodeType, - final Integer headerColor) - { + final Integer headerColor) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); @@ -502,11 +478,10 @@ public class DBHelper extends SQLiteOpenHelper return (rowsUpdated == 1); } - public boolean updateLoyaltyCardStarStatus(final int id, final int starStatus) - { + public boolean updateLoyaltyCardStarStatus(final int id, final int starStatus) { SQLiteDatabase db = getWritableDatabase(); ContentValues contentValues = new ContentValues(); - contentValues.put(LoyaltyCardDbIds.STAR_STATUS,starStatus); + contentValues.put(LoyaltyCardDbIds.STAR_STATUS, starStatus); int rowsUpdated = db.update(LoyaltyCardDbIds.TABLE, contentValues, whereAttrs(LoyaltyCardDbIds.ID), withArgs(id)); @@ -523,27 +498,25 @@ public class DBHelper extends SQLiteOpenHelper return (rowsUpdated == 1); } - public boolean updateLoyaltyCardZoomLevel(int loyaltyCardId, int zoomLevel){ + public boolean updateLoyaltyCardZoomLevel(int loyaltyCardId, int zoomLevel) { SQLiteDatabase db = getWritableDatabase(); ContentValues contentValues = new ContentValues(); - contentValues.put(LoyaltyCardDbIds.ZOOM_LEVEL,zoomLevel); - Log.d("updateLoyaltyCardZLevel","Card Id = "+loyaltyCardId+" Zoom level= "+zoomLevel); - int rowsUpdated = db.update(LoyaltyCardDbIds.TABLE,contentValues, + contentValues.put(LoyaltyCardDbIds.ZOOM_LEVEL, zoomLevel); + Log.d("updateLoyaltyCardZLevel", "Card Id = " + loyaltyCardId + " Zoom level= " + zoomLevel); + int rowsUpdated = db.update(LoyaltyCardDbIds.TABLE, contentValues, whereAttrs(LoyaltyCardDbIds.ID), withArgs(loyaltyCardId)); - Log.d("updateLoyaltyCardZLevel","Rows changed = "+rowsUpdated); + Log.d("updateLoyaltyCardZLevel", "Rows changed = " + rowsUpdated); return (rowsUpdated == 1); } - public LoyaltyCard getLoyaltyCard(final int id) - { + public LoyaltyCard getLoyaltyCard(final int id) { SQLiteDatabase db = getReadableDatabase(); Cursor data = db.query(LoyaltyCardDbIds.TABLE, null, whereAttrs(LoyaltyCardDbIds.ID), withArgs(id), null, null, null); LoyaltyCard card = null; - if(data.getCount() == 1) - { + if (data.getCount() == 1) { data.moveToFirst(); card = LoyaltyCard.toLoyaltyCard(data); } @@ -553,8 +526,7 @@ public class DBHelper extends SQLiteOpenHelper return card; } - public List getLoyaltyCardGroups(final int id) - { + public List getLoyaltyCardGroups(final int id) { SQLiteDatabase db = getReadableDatabase(); Cursor data = db.rawQuery("select * from " + LoyaltyCardDbGroups.TABLE + " g " + " LEFT JOIN " + LoyaltyCardDbIdsGroups.TABLE + " ig ON ig." + LoyaltyCardDbIdsGroups.groupID + " = g." + LoyaltyCardDbGroups.ID + @@ -579,8 +551,7 @@ public class DBHelper extends SQLiteOpenHelper return groups; } - public void setLoyaltyCardGroups(final int id, List groups) - { + public void setLoyaltyCardGroups(final int id, List groups) { SQLiteDatabase db = getWritableDatabase(); // First delete lookup table entries associated with this card @@ -597,8 +568,7 @@ public class DBHelper extends SQLiteOpenHelper } } - public void setLoyaltyCardGroups(final SQLiteDatabase db, final int id, List groups) - { + public void setLoyaltyCardGroups(final SQLiteDatabase db, final int id, List groups) { // First delete lookup table entries associated with this card db.delete(LoyaltyCardDbIdsGroups.TABLE, whereAttrs(LoyaltyCardDbIdsGroups.cardID), @@ -613,8 +583,7 @@ public class DBHelper extends SQLiteOpenHelper } } - public boolean deleteLoyaltyCard(final int id) - { + public boolean deleteLoyaltyCard(final int id) { SQLiteDatabase db = getWritableDatabase(); // Delete card int rowsDeleted = db.delete(LoyaltyCardDbIds.TABLE, @@ -642,8 +611,7 @@ public class DBHelper extends SQLiteOpenHelper return (rowsDeleted == 1); } - public Cursor getLoyaltyCardCursor() - { + public Cursor getLoyaltyCardCursor() { // An empty string will match everything return getLoyaltyCardCursor(""); } @@ -654,8 +622,7 @@ public class DBHelper extends SQLiteOpenHelper * @param filter * @return Cursor */ - public Cursor getLoyaltyCardCursor(final String filter) - { + public Cursor getLoyaltyCardCursor(final String filter) { return getLoyaltyCardCursor(filter, null); } @@ -666,8 +633,7 @@ public class DBHelper extends SQLiteOpenHelper * @param group * @return Cursor */ - public Cursor getLoyaltyCardCursor(final String filter, Group group) - { + public Cursor getLoyaltyCardCursor(final String filter, Group group) { return getLoyaltyCardCursor(filter, group, LoyaltyCardOrder.Alpha, LoyaltyCardOrderDirection.Ascending); } @@ -715,7 +681,7 @@ public class DBHelper extends SQLiteOpenHelper " (CASE WHEN " + LoyaltyCardDbIds.TABLE + "." + orderField + " IS NULL THEN 1 ELSE 0 END), " + LoyaltyCardDbIds.TABLE + "." + orderField + " COLLATE NOCASE " + getDbDirection(order, direction) + ", " + LoyaltyCardDbIds.TABLE + "." + LoyaltyCardDbIds.STORE + " COLLATE NOCASE ASC " + - limitString, filter.trim().isEmpty() ? null : new String[] { TextUtils.join("* ", filter.split(" ")) + '*' }, null); + limitString, filter.trim().isEmpty() ? null : new String[]{TextUtils.join("* ", filter.split(" ")) + '*'}, null); } /** @@ -723,8 +689,7 @@ public class DBHelper extends SQLiteOpenHelper * * @return Integer */ - public int getLoyaltyCardCount() - { + public int getLoyaltyCardCount() { SQLiteDatabase db = getReadableDatabase(); return (int) DatabaseUtils.queryNumEntries(db, LoyaltyCardDbIds.TABLE); } @@ -734,8 +699,7 @@ public class DBHelper extends SQLiteOpenHelper * * @return Cursor */ - public Cursor getGroupCursor() - { + public Cursor getGroupCursor() { SQLiteDatabase db = getReadableDatabase(); return db.rawQuery("select * from " + LoyaltyCardDbGroups.TABLE + @@ -761,13 +725,11 @@ public class DBHelper extends SQLiteOpenHelper return groups; } - public void reorderGroups(final List groups) - { + public void reorderGroups(final List groups) { Integer order = 0; SQLiteDatabase db = getWritableDatabase(); - for (Group group : groups) - { + for (Group group : groups) { ContentValues contentValues = new ContentValues(); contentValues.put(LoyaltyCardDbGroups.ORDER, order); @@ -779,15 +741,13 @@ public class DBHelper extends SQLiteOpenHelper } } - public Group getGroup(final String groupName) - { + public Group getGroup(final String groupName) { SQLiteDatabase db = getReadableDatabase(); Cursor data = db.query(LoyaltyCardDbGroups.TABLE, null, whereAttrs(LoyaltyCardDbGroups.ID), withArgs(groupName), null, null, null); Group group = null; - if(data.getCount() == 1) - { + if (data.getCount() == 1) { data.moveToFirst(); group = Group.toGroup(data); } @@ -796,14 +756,12 @@ public class DBHelper extends SQLiteOpenHelper return group; } - public int getGroupCount() - { + public int getGroupCount() { SQLiteDatabase db = getReadableDatabase(); return (int) DatabaseUtils.queryNumEntries(db, LoyaltyCardDbGroups.TABLE); } - public List getGroupCardIds(final String groupName) - { + public List getGroupCardIds(final String groupName) { SQLiteDatabase db = getReadableDatabase(); Cursor data = db.query(LoyaltyCardDbIdsGroups.TABLE, withArgs(LoyaltyCardDbIdsGroups.cardID), whereAttrs(LoyaltyCardDbIdsGroups.groupID), withArgs(groupName), null, null, null); @@ -824,8 +782,7 @@ public class DBHelper extends SQLiteOpenHelper return cardIds; } - public long insertGroup(final String name) - { + public long insertGroup(final String name) { if (name.isEmpty()) return -1; SQLiteDatabase db = getWritableDatabase(); @@ -835,8 +792,7 @@ public class DBHelper extends SQLiteOpenHelper return db.insert(LoyaltyCardDbGroups.TABLE, null, contentValues); } - public boolean insertGroup(final SQLiteDatabase db, final String name) - { + public boolean insertGroup(final SQLiteDatabase db, final String name) { ContentValues contentValues = new ContentValues(); contentValues.put(LoyaltyCardDbGroups.ID, name); contentValues.put(LoyaltyCardDbGroups.ORDER, getGroupCount()); @@ -844,8 +800,7 @@ public class DBHelper extends SQLiteOpenHelper return newId != -1; } - public boolean updateGroup(final String groupName, final String newName) - { + public boolean updateGroup(final String groupName, final String newName) { if (newName.isEmpty()) return false; boolean success = false; @@ -881,8 +836,7 @@ public class DBHelper extends SQLiteOpenHelper return success; } - public boolean deleteGroup(final String groupName) - { + public boolean deleteGroup(final String groupName) { boolean success = false; SQLiteDatabase db = getWritableDatabase(); @@ -913,8 +867,7 @@ public class DBHelper extends SQLiteOpenHelper return success; } - public int getGroupCardCount(final String groupName) - { + public int getGroupCardCount(final String groupName) { SQLiteDatabase db = getReadableDatabase(); return (int) DatabaseUtils.queryNumEntries(db, LoyaltyCardDbIdsGroups.TABLE, diff --git a/app/src/main/java/protect/card_locker/FormatException.java b/app/src/main/java/protect/card_locker/FormatException.java index db23ebfd4..a44286a80 100644 --- a/app/src/main/java/protect/card_locker/FormatException.java +++ b/app/src/main/java/protect/card_locker/FormatException.java @@ -5,15 +5,12 @@ package protect.card_locker; * encountered with the format of data being * imported or exported. */ -public class FormatException extends Exception -{ - public FormatException(String message) - { +public class FormatException extends Exception { + public FormatException(String message) { super(message); } - public FormatException(String message, Exception rootCause) - { + public FormatException(String message, Exception rootCause) { super(message, rootCause); } } diff --git a/app/src/main/java/protect/card_locker/Group.java b/app/src/main/java/protect/card_locker/Group.java index f39de2b50..90d8da69d 100644 --- a/app/src/main/java/protect/card_locker/Group.java +++ b/app/src/main/java/protect/card_locker/Group.java @@ -4,8 +4,7 @@ import android.database.Cursor; import androidx.annotation.Nullable; -public class Group -{ +public class Group { public final String _id; public final int order; @@ -14,8 +13,7 @@ public class Group this.order = order; } - public static Group toGroup(Cursor cursor) - { + public static Group toGroup(Cursor cursor) { String _id = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbGroups.ID)); int order = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbGroups.ORDER)); @@ -24,18 +22,18 @@ public class Group @Override public boolean equals(@Nullable Object obj) { - if (obj == null){ + if (obj == null) { return false; } - if (!(obj instanceof Group)){ + if (!(obj instanceof Group)) { return false; } - Group anotherGroup = (Group)obj; + Group anotherGroup = (Group) obj; return _id.equals(anotherGroup._id) && order == anotherGroup.order; } @Override - public int hashCode(){ + public int hashCode() { String combined = _id + "_" + order; return combined.hashCode(); } diff --git a/app/src/main/java/protect/card_locker/GroupCursorAdapter.java b/app/src/main/java/protect/card_locker/GroupCursorAdapter.java index 1e89bb091..05cc1d9f6 100644 --- a/app/src/main/java/protect/card_locker/GroupCursorAdapter.java +++ b/app/src/main/java/protect/card_locker/GroupCursorAdapter.java @@ -12,8 +12,7 @@ import androidx.appcompat.widget.AppCompatImageButton; import androidx.recyclerview.widget.RecyclerView; import protect.card_locker.preferences.Settings; -class GroupCursorAdapter extends BaseCursorAdapter -{ +class GroupCursorAdapter extends BaseCursorAdapter { Settings mSettings; private Cursor mCursor; private final Context mContext; @@ -39,14 +38,12 @@ class GroupCursorAdapter extends BaseCursorAdapter mListener.onMoveDownButtonClicked(inputHolder.itemView)); inputHolder.mMoveUp.setOnClickListener(view -> mListener.onMoveUpButtonClicked(inputHolder.itemView)); inputHolder.mEdit.setOnClickListener(view -> mListener.onEditButtonClicked(inputHolder.itemView)); inputHolder.mDelete.setOnClickListener(view -> mListener.onDeleteButtonClicked(inputHolder.itemView)); } - public interface GroupAdapterListener - { + public interface GroupAdapterListener { void onMoveDownButtonClicked(View view); + void onMoveUpButtonClicked(View view); + void onEditButtonClicked(View view); + void onDeleteButtonClicked(View view); } - public static class GroupListItemViewHolder extends RecyclerView.ViewHolder - { + public static class GroupListItemViewHolder extends RecyclerView.ViewHolder { public TextView mName, mCardCount; public AppCompatImageButton mMoveUp, mMoveDown, mEdit, mDelete; diff --git a/app/src/main/java/protect/card_locker/ImportExportActivity.java b/app/src/main/java/protect/card_locker/ImportExportActivity.java index 444cc2d9e..8af55a978 100644 --- a/app/src/main/java/protect/card_locker/ImportExportActivity.java +++ b/app/src/main/java/protect/card_locker/ImportExportActivity.java @@ -31,7 +31,6 @@ import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; - import protect.card_locker.async.TaskHandler; import protect.card_locker.importexport.DataFormat; import protect.card_locker.importexport.ImportExportResult; diff --git a/app/src/main/java/protect/card_locker/ImportURIHelper.java b/app/src/main/java/protect/card_locker/ImportURIHelper.java index 812d5665c..4cb476708 100644 --- a/app/src/main/java/protect/card_locker/ImportURIHelper.java +++ b/app/src/main/java/protect/card_locker/ImportURIHelper.java @@ -4,8 +4,6 @@ import android.content.Context; import android.content.Intent; import android.net.Uri; -import com.google.zxing.BarcodeFormat; - import java.io.InvalidObjectException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; @@ -57,7 +55,7 @@ public class ImportURIHelper { } public LoyaltyCard parse(Uri uri) throws InvalidObjectException { - if(!isImportUri(uri)) { + if (!isImportUri(uri)) { throw new InvalidObjectException("Not an import URI"); } @@ -92,37 +90,33 @@ public class ImportURIHelper { String note = kv.get(NOTE); String cardId = kv.get(CARD_ID); String barcodeId = kv.get(BARCODE_ID); - if (store == null || note == null || cardId == null) throw new InvalidObjectException("Not a valid import URI: " + uri.toString()); + if (store == null || note == null || cardId == null) + throw new InvalidObjectException("Not a valid import URI: " + uri.toString()); String unparsedBarcodeType = kv.get(BARCODE_TYPE); - if(unparsedBarcodeType != null && !unparsedBarcodeType.equals("")) - { + if (unparsedBarcodeType != null && !unparsedBarcodeType.equals("")) { barcodeType = CatimaBarcode.fromName(unparsedBarcodeType); } String unparsedBalance = kv.get(BALANCE); - if(unparsedBalance != null && !unparsedBalance.equals("")) - { + if (unparsedBalance != null && !unparsedBalance.equals("")) { balance = new BigDecimal(unparsedBalance); } String unparsedBalanceType = kv.get(BALANCE_TYPE); - if (unparsedBalanceType != null && !unparsedBalanceType.equals("")) - { + if (unparsedBalanceType != null && !unparsedBalanceType.equals("")) { balanceType = Currency.getInstance(unparsedBalanceType); } String unparsedExpiry = kv.get(EXPIRY); - if(unparsedExpiry != null && !unparsedExpiry.equals("")) - { + if (unparsedExpiry != null && !unparsedExpiry.equals("")) { expiry = new Date(Long.parseLong(unparsedExpiry)); } String unparsedHeaderColor = kv.get(HEADER_COLOR); - if(unparsedHeaderColor != null) - { + if (unparsedHeaderColor != null) { headerColor = Integer.parseInt(unparsedHeaderColor); } - return new LoyaltyCard(-1, store, note, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, 0, Utils.getUnixTime(),100); + return new LoyaltyCard(-1, store, note, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, 0, Utils.getUnixTime(), 100); } catch (NullPointerException | NumberFormatException | UnsupportedEncodingException ex) { throw new InvalidObjectException("Not a valid import URI"); } @@ -159,14 +153,14 @@ public class ImportURIHelper { fragment = appendFragment(fragment, EXPIRY, String.valueOf(loyaltyCard.expiry.getTime())); } fragment = appendFragment(fragment, CARD_ID, loyaltyCard.cardId); - if(loyaltyCard.barcodeId != null) { + if (loyaltyCard.barcodeId != null) { fragment = appendFragment(fragment, BARCODE_ID, loyaltyCard.barcodeId); } - if(loyaltyCard.barcodeType != null) { + if (loyaltyCard.barcodeType != null) { fragment = appendFragment(fragment, BARCODE_TYPE, loyaltyCard.barcodeType.name()); } - if(loyaltyCard.headerColor != null) { + if (loyaltyCard.headerColor != null) { fragment = appendFragment(fragment, HEADER_COLOR, loyaltyCard.headerColor.toString()); } // Star status will not be exported diff --git a/app/src/main/java/protect/card_locker/LetterBitmap.java b/app/src/main/java/protect/card_locker/LetterBitmap.java index 2afc75f2e..94b409168 100644 --- a/app/src/main/java/protect/card_locker/LetterBitmap.java +++ b/app/src/main/java/protect/card_locker/LetterBitmap.java @@ -18,8 +18,7 @@ import android.text.TextPaint; * alphabet or digit, if there is no letter or digit available, a default image * is shown instead. */ -class LetterBitmap -{ +class LetterBitmap { /** * The number of available tile colors @@ -37,39 +36,32 @@ class LetterBitmap /** * Constructor for LetterTileProvider * - * @param context The {@link Context} to use - * @param displayName The name used to create the letter for the tile - * @param key The key used to generate the background color for the tile + * @param context The {@link Context} to use + * @param displayName The name used to create the letter for the tile + * @param key The key used to generate the background color for the tile * @param tileLetterFontSize The font size used to display the letter - * @param width The desired width of the tile - * @param height The desired height of the tile - * @param backgroundColor (optional) color to use for background. - * @param textColor (optional) color to use for text. + * @param width The desired width of the tile + * @param height The desired height of the tile + * @param backgroundColor (optional) color to use for background. + * @param textColor (optional) color to use for text. */ public LetterBitmap(Context context, String displayName, String key, int tileLetterFontSize, - int width, int height, Integer backgroundColor, Integer textColor) - { + int width, int height, Integer backgroundColor, Integer textColor) { TextPaint paint = new TextPaint(); paint.setTypeface(Typeface.create("sans-serif-light", Typeface.BOLD)); - if(textColor != null) - { + if (textColor != null) { paint.setColor(textColor); - } - else - { + } else { paint.setColor(Color.WHITE); } paint.setTextAlign(Paint.Align.CENTER); paint.setAntiAlias(true); - if(backgroundColor == null) - { + if (backgroundColor == null) { mColor = getDefaultColor(context, key); - } - else - { + } else { mColor = backgroundColor; } @@ -80,7 +72,7 @@ class LetterBitmap c.setBitmap(mBitmap); c.drawColor(mColor); - char [] firstCharArray = new char[1]; + char[] firstCharArray = new char[1]; firstCharArray[0] = firstChar.toUpperCase().charAt(0); paint.setTextSize(tileLetterFontSize); @@ -97,16 +89,14 @@ class LetterBitmap * alphabet or digit, if there is no letter or digit available, a * default image is shown instead */ - public Bitmap getLetterTile() - { + public Bitmap getLetterTile() { return mBitmap; } /** * @return background color used for letter title. */ - public int getBackgroundColor() - { + public int getBackgroundColor() { return mColor; } @@ -115,8 +105,7 @@ class LetterBitmap * @return A new or previously chosen color for key used as the * tile background color */ - private static int pickColor(String key, TypedArray colors) - { + private static int pickColor(String key, TypedArray colors) { // String.hashCode() is not supposed to change across java versions, so // this should guarantee the same key always maps to the same color final int color = Math.abs(key.hashCode()) % NUM_OF_TILE_COLORS; @@ -127,8 +116,7 @@ class LetterBitmap * Determine the color which the letter tile will use if no default * color is provided. */ - public static int getDefaultColor(Context context, String key) - { + public static int getDefaultColor(Context context, String key) { final Resources res = context.getResources(); TypedArray colors = res.obtainTypedArray(R.array.letter_tile_colors); diff --git a/app/src/main/java/protect/card_locker/LoyaltyCard.java b/app/src/main/java/protect/card_locker/LoyaltyCard.java index 1ec44fa6d..06a0165a5 100644 --- a/app/src/main/java/protect/card_locker/LoyaltyCard.java +++ b/app/src/main/java/protect/card_locker/LoyaltyCard.java @@ -35,8 +35,7 @@ public class LoyaltyCard implements Parcelable { public LoyaltyCard(final int id, final String store, final String note, final Date expiry, final BigDecimal balance, final Currency balanceType, final String cardId, @Nullable final String barcodeId, @Nullable final CatimaBarcode barcodeType, - @Nullable final Integer headerColor, final int starStatus, final long lastUsed,final int zoomLevel) - { + @Nullable final Integer headerColor, final int starStatus, final long lastUsed, final int zoomLevel) { this.id = id; this.store = store; this.note = note; @@ -88,8 +87,7 @@ public class LoyaltyCard implements Parcelable { parcel.writeInt(zoomLevel); } - public static LoyaltyCard toLoyaltyCard(Cursor cursor) - { + public static LoyaltyCard toLoyaltyCard(Cursor cursor) { int id = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.ID)); String store = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.STORE)); String note = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.NOTE)); @@ -110,27 +108,23 @@ public class LoyaltyCard implements Parcelable { Date expiry = null; Integer headerColor = null; - if (cursor.isNull(barcodeTypeColumn) == false) - { + if (cursor.isNull(barcodeTypeColumn) == false) { barcodeType = CatimaBarcode.fromName(cursor.getString(barcodeTypeColumn)); } - if (cursor.isNull(balanceTypeColumn) == false) - { + if (cursor.isNull(balanceTypeColumn) == false) { balanceType = Currency.getInstance(cursor.getString(balanceTypeColumn)); } - if(expiryLong > 0) - { + if (expiryLong > 0) { expiry = new Date(expiryLong); } - if(cursor.isNull(headerColorColumn) == false) - { + if (cursor.isNull(headerColorColumn) == false) { headerColor = cursor.getInt(headerColorColumn); } - return new LoyaltyCard(id, store, note, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, starred, lastUsed,zoomLevel); + return new LoyaltyCard(id, store, note, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, starred, lastUsed, zoomLevel); } @Override diff --git a/app/src/main/java/protect/card_locker/LoyaltyCardCursorAdapter.java b/app/src/main/java/protect/card_locker/LoyaltyCardCursorAdapter.java index f259768c1..413028ee1 100644 --- a/app/src/main/java/protect/card_locker/LoyaltyCardCursorAdapter.java +++ b/app/src/main/java/protect/card_locker/LoyaltyCardCursorAdapter.java @@ -25,7 +25,6 @@ import java.util.ArrayList; import androidx.core.graphics.BlendModeColorFilterCompat; import androidx.core.graphics.BlendModeCompat; import androidx.recyclerview.widget.RecyclerView; - import protect.card_locker.preferences.Settings; public class LoyaltyCardCursorAdapter extends BaseCursorAdapter { @@ -92,11 +91,11 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter{ + mPhotoTakerLauncher = registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> { if (result) { startCropper(getCacheDir() + "/" + TEMP_CAMERA_IMAGE_NAME); } @@ -575,20 +573,20 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { // android 11: wanted to swap it to ActivityResultContracts.GetContent but then it shows a file browsers that shows image mime types, offering gallery in the file browser mPhotoPickerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == RESULT_OK) { - Intent intent = result.getData(); - if (intent == null){ - Log.d("photo picker", "photo picker returned without an intent"); - return; - } - Uri uri = intent.getData(); - startCropperUri(uri); + Intent intent = result.getData(); + if (intent == null) { + Log.d("photo picker", "photo picker returned without an intent"); + return; + } + Uri uri = intent.getData(); + startCropperUri(uri); } }); mCardIdAndBarCodeEditorLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == RESULT_OK) { Intent intent = result.getData(); - if (intent == null){ + if (intent == null) { Log.d("barcode card id editor", "barcode and card id editor picker returned without an intent"); return; } @@ -602,13 +600,13 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { mCropperLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { Intent intent = result.getData(); - if (intent == null){ + if (intent == null) { Log.d("cropper", "ucrop returned a null intent"); return; } if (result.getResultCode() == Activity.RESULT_OK) { Uri debugUri = UCrop.getOutput(intent); - if (debugUri == null){ + if (debugUri == null) { throw new RuntimeException("ucrop returned success but not destination uri!"); } Log.d("cropper", "ucrop produced image at " + debugUri); @@ -629,9 +627,9 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { } else { Toast.makeText(LoyaltyCardEditActivity.this, R.string.errorReadingImage, Toast.LENGTH_LONG).show(); } - }else if(result.getResultCode() == UCrop.RESULT_ERROR){ + } else if (result.getResultCode() == UCrop.RESULT_ERROR) { Throwable e = UCrop.getError(intent); - if (e == null){ + if (e == null) { throw new RuntimeException("ucrop returned error state but not an error!"); } Log.e("cropper error", e.toString()); @@ -645,23 +643,23 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { // ucrop 2.2.6 initial aspect ratio is glitched when 0x0 is used as the initial ratio option // https://github.com/Yalantis/uCrop/blob/281c8e6438d81f464d836fc6b500517144af264a/ucrop/src/main/java/com/yalantis/ucrop/UCropActivity.java#L264 // so source width height has to be provided for now, depending on whether future versions of ucrop will support 0x0 as the default option - private void setCropperOptions(float sourceWidth, float sourceHeight){ + private void setCropperOptions(float sourceWidth, float sourceHeight) { mCropperOptions.setCompressionFormat(TEMP_CROP_IMAGE_FORMAT); mCropperOptions.setFreeStyleCropEnabled(true); mCropperOptions.setHideBottomControls(false); // default aspect ratio workaround int selectedByDefault = 1; - if (sourceWidth == 0f && sourceHeight == 0f){ + if (sourceWidth == 0f && sourceHeight == 0f) { selectedByDefault = 0; } mCropperOptions.setAspectRatioOptions(selectedByDefault, new AspectRatio(null, 1, 1), new AspectRatio(getResources().getString(R.string.ucrop_label_original).toUpperCase(), sourceWidth, sourceHeight), - new AspectRatio(getResources().getString(R.string.card),85.6f,53.98f ) + new AspectRatio(getResources().getString(R.string.card), 85.6f, 53.98f) ); } - private void setCropperTheme(){ + private void setCropperTheme() { mCropperOptions.setToolbarColor(getResources().getColor(R.color.colorPrimary)); mCropperOptions.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); mCropperOptions.setToolbarWidgetColor(Color.WHITE); @@ -676,15 +674,15 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { extractIntentFields(intent); } - private boolean requestedFrontImage(){ + private boolean requestedFrontImage() { return mRequestedImage == Utils.CARD_IMAGE_FROM_CAMERA_FRONT || mRequestedImage == Utils.CARD_IMAGE_FROM_FILE_FRONT; } - private boolean croppedFrontImage(){ + private boolean croppedFrontImage() { return mCropperFinishedType == Utils.CARD_IMAGE_FROM_CAMERA_FRONT || mCropperFinishedType == Utils.CARD_IMAGE_FROM_FILE_FRONT; } - private boolean croppedBackImage(){ + private boolean croppedBackImage() { return mCropperFinishedType == Utils.CARD_IMAGE_FROM_CAMERA_BACK || mCropperFinishedType == Utils.CARD_IMAGE_FROM_FILE_BACK; } @@ -717,12 +715,12 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { } } else { // New card, use default values - tempLoyaltyCard = new LoyaltyCard(-1, "", "", null, new BigDecimal("0"), null, "", null, null, null, 0, Utils.getUnixTime(),100); + tempLoyaltyCard = new LoyaltyCard(-1, "", "", null, new BigDecimal("0"), null, "", null, null, null, 0, Utils.getUnixTime(), 100); } } - if(!initDone) { + if (!initDone) { if (updateLoyaltyCard) { setTitle(R.string.editCardTitle); if (!mFrontImageUnsaved && !croppedFrontImage() && !mFrontImageRemoved) { @@ -731,13 +729,13 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { if (!mBackImageUnsaved && !croppedBackImage() && !mBackImageRemoved) { setCardImage(cardImageBack, Utils.retrieveCardImage(this, tempLoyaltyCard.id, false)); } - }else{ + } else { setTitle(R.string.addCardTitle); } - if(mFrontImageUnsaved && !croppedFrontImage()){ + if (mFrontImageUnsaved && !croppedFrontImage()) { setCardImage(cardImageFront, Utils.loadTempImage(this, TEMP_UNSAVED_FRONT_IMAGE_NAME)); } - if(mBackImageUnsaved && !croppedBackImage()){ + if (mBackImageUnsaved && !croppedBackImage()) { setCardImage(cardImageBack, Utils.loadTempImage(this, TEMP_UNSAVED_BACK_IMAGE_NAME)); } } @@ -977,7 +975,6 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { } - private void takePhotoForCard(int type) throws IOException { Uri photoURI = FileProvider.getUriForFile(LoyaltyCardEditActivity.this, BuildConfig.APPLICATION_ID, Utils.createTempFile(this, TEMP_CAMERA_IMAGE_NAME)); mRequestedImage = type; @@ -1005,10 +1002,10 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { if (targetView.getTag() != null) { cardOptions.put(getString(R.string.removeImage), () -> { setCardImage(targetView, null); - if (targetView == cardImageFront){ + if (targetView == cardImageFront) { mFrontImageRemoved = true; mFrontImageUnsaved = false; - }else{ + } else { mBackImageRemoved = true; mBackImageUnsaved = false; } @@ -1224,18 +1221,19 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { return super.onOptionsItemSelected(item); } - public void startCropper(String sourceImagePath){ + public void startCropper(String sourceImagePath) { startCropperUri(Uri.parse("file://" + sourceImagePath)); } - public void startCropperUri(Uri sourceUri){ + + public void startCropperUri(Uri sourceUri) { Log.d("cropper", "launching cropper with image " + sourceUri.getPath()); File cropOutput = Utils.createTempFile(this, TEMP_CROP_IMAGE_NAME); Uri destUri = Uri.parse("file://" + cropOutput.getAbsolutePath()); Log.d("cropper", "asking cropper to output to " + destUri.toString()); - if(mRequestedImage == Utils.CARD_IMAGE_FROM_CAMERA_FRONT || mRequestedImage == Utils.CARD_IMAGE_FROM_FILE_FRONT){ + if (mRequestedImage == Utils.CARD_IMAGE_FROM_CAMERA_FRONT || mRequestedImage == Utils.CARD_IMAGE_FROM_FILE_FRONT) { mCropperOptions.setToolbarTitle(getResources().getString(R.string.setFrontImage)); - }else{ + } else { mCropperOptions.setToolbarTitle(getResources().getString(R.string.setBackImage)); } @@ -1243,22 +1241,22 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { Bitmap image = null; try { image = BitmapFactory.decodeStream(getContentResolver().openInputStream(sourceUri)); - }catch(FileNotFoundException e){ + } catch (FileNotFoundException e) { e.printStackTrace(); Log.d("cropper", "failed opening bitmap for initial width and height for ucrop " + sourceUri.toString()); } - if (image == null){ + if (image == null) { Log.d("cropper", "failed loading bitmap for initial width and height for ucrop " + sourceUri.toString()); setCropperOptions(0f, 0f); - }else{ + } else { try { Bitmap imageRotated = Utils.rotateBitmap(image, new ExifInterface(getContentResolver().openInputStream(sourceUri))); setCropperOptions(imageRotated.getWidth(), imageRotated.getHeight()); - }catch(FileNotFoundException e){ + } catch (FileNotFoundException e) { e.printStackTrace(); Log.d("cropper", "failed opening image for exif reading before setting initial width and height for ucrop"); setCropperOptions(image.getWidth(), image.getHeight()); - }catch(IOException e){ + } catch (IOException e) { e.printStackTrace(); Log.d("cropper", "exif reading failed before setting initial width and height for ucrop"); setCropperOptions(image.getWidth(), image.getHeight()); @@ -1270,7 +1268,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { sourceUri, destUri ).withOptions(mCropperOptions) - .getIntent(this) + .getIntent(this) ); return; } @@ -1296,7 +1294,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity { private void generateBarcode(String cardIdString, CatimaBarcode barcodeFormat) { mTasks.flushTaskList(TaskHandler.TYPE.BARCODE, true, false, false); - + if (barcodeImage.getHeight() == 0) { Log.d(TAG, "ImageView size is not known known at start, waiting for load"); // The size of the ImageView is not yet available as it has not diff --git a/app/src/main/java/protect/card_locker/LoyaltyCardLockerApplication.java b/app/src/main/java/protect/card_locker/LoyaltyCardLockerApplication.java index c031f7904..4ceb46994 100644 --- a/app/src/main/java/protect/card_locker/LoyaltyCardLockerApplication.java +++ b/app/src/main/java/protect/card_locker/LoyaltyCardLockerApplication.java @@ -3,7 +3,6 @@ package protect.card_locker; import android.app.Application; import androidx.appcompat.app.AppCompatDelegate; - import protect.card_locker.preferences.Settings; public class LoyaltyCardLockerApplication extends Application { diff --git a/app/src/main/java/protect/card_locker/LoyaltyCardViewActivity.java b/app/src/main/java/protect/card_locker/LoyaltyCardViewActivity.java index 5daead381..15c0c26b9 100644 --- a/app/src/main/java/protect/card_locker/LoyaltyCardViewActivity.java +++ b/app/src/main/java/protect/card_locker/LoyaltyCardViewActivity.java @@ -47,7 +47,6 @@ import androidx.constraintlayout.widget.Guideline; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.DrawableCompat; import androidx.core.widget.TextViewCompat; - import protect.card_locker.async.TaskHandler; import protect.card_locker.preferences.Settings; @@ -194,9 +193,9 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements Drawable unwrappedIcon = AppCompatResources.getDrawable(this, active ? R.drawable.active_dot : R.drawable.inactive_dot); assert unwrappedIcon != null; Drawable wrappedIcon = DrawableCompat.wrap(unwrappedIcon); - if (darkMode){ + if (darkMode) { DrawableCompat.setTint(wrappedIcon, Color.WHITE); - }else{ + } else { DrawableCompat.setTint(wrappedIcon, Color.BLACK); } @@ -269,7 +268,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements barcodeScaler.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!fromUser){ + if (!fromUser) { Log.d(TAG, "non user triggered onProgressChanged, ignoring, progress is " + progress); return; } @@ -796,7 +795,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements /** * When enabled, hides the status bar and moves the barcode to the top of the screen. - * + *

* The purpose of this function is to make sure the barcode can be scanned from the phone * by machines which offer no space to insert the complete device. */ @@ -882,6 +881,6 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements ); } - Log.d("setFullScreen","Is full screen enabled? "+enabled+" Zoom Level = "+barcodeScaler.getProgress()); + Log.d("setFullScreen", "Is full screen enabled? " + enabled + " Zoom Level = " + barcodeScaler.getProgress()); } } diff --git a/app/src/main/java/protect/card_locker/MainActivity.java b/app/src/main/java/protect/card_locker/MainActivity.java index 787b805a3..9722818f3 100644 --- a/app/src/main/java/protect/card_locker/MainActivity.java +++ b/app/src/main/java/protect/card_locker/MainActivity.java @@ -6,7 +6,6 @@ import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.content.res.Configuration; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.os.Bundle; @@ -31,13 +30,11 @@ import androidx.appcompat.app.AlertDialog; import androidx.appcompat.view.ActionMode; import androidx.appcompat.widget.SearchView; import androidx.appcompat.widget.Toolbar; -import androidx.core.app.ActivityCompat; import androidx.core.splashscreen.SplashScreen; import androidx.recyclerview.widget.RecyclerView; import protect.card_locker.preferences.SettingsActivity; -public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCardCursorAdapter.CardAdapterListener, GestureDetector.OnGestureListener -{ +public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCardCursorAdapter.CardAdapterListener, GestureDetector.OnGestureListener { private static final String TAG = "Catima"; private final DBHelper mDB = new DBHelper(this); @@ -55,8 +52,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard private View mNoMatchingCardsText; private View mNoGroupCardsText; - private ActionMode.Callback mCurrentActionModeCallback = new ActionMode.Callback() - { + private ActionMode.Callback mCurrentActionModeCallback = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode inputMode, Menu inputMenu) { inputMode.getMenuInflater().inflate(R.menu.card_longclick_menu, inputMenu); @@ -64,8 +60,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } @Override - public boolean onPrepareActionMode(ActionMode inputMode, Menu inputMenu) - { + public boolean onPrepareActionMode(ActionMode inputMode, Menu inputMenu) { return false; } @@ -109,7 +104,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } inputMode.finish(); return true; - } else if(inputItem.getItemId() == R.id.action_edit) { + } else if (inputItem.getItemId() == R.id.action_edit) { if (mAdapter.getSelectedItemCount() != 1) { throw new IllegalArgumentException("Cannot edit more than 1 card at a time"); } @@ -122,7 +117,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard startActivity(intent); inputMode.finish(); return true; - } else if(inputItem.getItemId() == R.id.action_delete) { + } else if (inputItem.getItemId() == R.id.action_delete) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // The following may seem weird, but it is necessary to give translators enough flexibility. // For example, in Russian, Android's plural quantity "one" actually refers to "any number ending on 1 but not ending in 11". @@ -165,15 +160,12 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } @Override - public void onDestroyActionMode(ActionMode inputMode) - { + public void onDestroyActionMode(ActionMode inputMode) { mAdapter.clearSelections(); mCurrentActionMode = null; - mCardList.post(new Runnable() - { + mCardList.post(new Runnable() { @Override - public void run() - { + public void run() { mAdapter.resetAnimationIndex(); } }); @@ -181,8 +173,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard }; @Override - protected void onCreate(Bundle inputSavedInstanceState) - { + protected void onCreate(Bundle inputSavedInstanceState) { super.onCreate(inputSavedInstanceState); SplashScreen.installSplashScreen(this); setTitle(R.string.app_name); @@ -195,7 +186,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard @Override public void onTabSelected(TabLayout.Tab tab) { selectedTab = tab.getPosition(); - Log.d("onTabSelected","Tab Position "+tab.getPosition()); + Log.d("onTabSelected", "Tab Position " + tab.getPosition()); mGroup = tab.getTag(); updateLoyaltyCardList(); // Store active tab in Shared Preference to restore next app launch @@ -272,22 +263,18 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } @Override - protected void onResume() - { + protected void onResume() { super.onResume(); - if(mCurrentActionMode != null) - { + if (mCurrentActionMode != null) { mAdapter.clearSelections(); mCurrentActionMode.finish(); } - if (mMenu != null) - { + if (mMenu != null) { SearchView searchView = (SearchView) mMenu.findItem(R.id.action_search).getActionView(); - if (!searchView.isIconified()) - { + if (!searchView.isIconified()) { mFilter = searchView.getQuery().toString(); } } @@ -307,7 +294,8 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard try { mOrder = DBHelper.LoyaltyCardOrder.valueOf(sortPref.getString(getString(R.string.sharedpreference_sort_order), null)); mOrderDirection = DBHelper.LoyaltyCardOrderDirection.valueOf(sortPref.getString(getString(R.string.sharedpreference_sort_direction), null)); - } catch (IllegalArgumentException | NullPointerException ignored) {} + } catch (IllegalArgumentException | NullPointerException ignored) { + } mGroup = null; @@ -345,8 +333,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard // We're coming back from another view so clear the search // We only do this now to prevent a flash of all entries right after picking one mFilter = ""; - if (mMenu != null) - { + if (mMenu != null) { MenuItem searchItem = mMenu.findItem(R.id.action_search); searchItem.collapseActionView(); } @@ -357,7 +344,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard BarcodeValues barcodeValues = Utils.parseSetBarcodeActivityResult(requestCode, resultCode, intent, this); - if(!barcodeValues.isEmpty()) { + if (!barcodeValues.isEmpty()) { Intent newIntent = new Intent(getApplicationContext(), LoyaltyCardEditActivity.class); Bundle newBundle = new Bundle(); newBundle.putString(LoyaltyCardEditActivity.BUNDLE_BARCODETYPE, barcodeValues.format()); @@ -372,8 +359,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } @Override - public void onBackPressed() - { + public void onBackPressed() { if (mMenu != null) { SearchView searchView = (SearchView) mMenu.findItem(R.id.action_search).getActionView(); @@ -394,20 +380,16 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard mAdapter.swapCursor(mDB.getLoyaltyCardCursor(mFilter, group, mOrder, mOrderDirection)); - if(mDB.getLoyaltyCardCount() > 0) - { + if (mDB.getLoyaltyCardCount() > 0) { // We want the cardList to be visible regardless of the filtered match count // to ensure that the noMatchingCardsText doesn't end up being shown below // the keyboard mHelpText.setVisibility(View.GONE); mNoGroupCardsText.setVisibility(View.GONE); - if(mAdapter.getItemCount() > 0) - { + if (mAdapter.getItemCount() > 0) { mCardList.setVisibility(View.VISIBLE); mNoMatchingCardsText.setVisibility(View.GONE); - } - else - { + } else { mCardList.setVisibility(View.GONE); if (!mFilter.isEmpty()) { // Actual Empty Search Result @@ -419,9 +401,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard mNoGroupCardsText.setVisibility(View.VISIBLE); } } - } - else - { + } else { mCardList.setVisibility(View.GONE); mHelpText.setVisibility(View.VISIBLE); mNoMatchingCardsText.setVisibility(View.GONE); @@ -433,8 +413,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } } - public void updateTabGroups(TabLayout groupsTabLayout) - { + public void updateTabGroups(TabLayout groupsTabLayout) { final DBHelper db = new DBHelper(this); List newGroups = db.getGroups(); @@ -463,15 +442,13 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } @Override - public boolean onCreateOptionsMenu(Menu inputMenu) - { + public boolean onCreateOptionsMenu(Menu inputMenu) { this.mMenu = inputMenu; getMenuInflater().inflate(R.menu.main_menu, inputMenu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); - if (searchManager != null) - { + if (searchManager != null) { SearchView searchView = (SearchView) inputMenu.findItem(R.id.action_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setSubmitButtonEnabled(false); @@ -481,17 +458,14 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard return false; }); - searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() - { + searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override - public boolean onQueryTextSubmit(String query) - { + public boolean onQueryTextSubmit(String query) { return false; } @Override - public boolean onQueryTextChange(String newText) - { + public boolean onQueryTextChange(String newText) { mFilter = newText; TabLayout groupsTabLayout = findViewById(R.id.groups); @@ -508,12 +482,10 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } @Override - public boolean onOptionsItemSelected(MenuItem inputItem) - { + public boolean onOptionsItemSelected(MenuItem inputItem) { int id = inputItem.getItemId(); - if (id == R.id.action_sort) - { + if (id == R.id.action_sort) { TabLayout.Tab tab = ((TabLayout) findViewById(R.id.groups)).getTabAt(selectedTab); AtomicInteger currentIndex = new AtomicInteger(); List loyaltyCardOrders = Arrays.asList(DBHelper.LoyaltyCardOrder.values()); @@ -536,10 +508,9 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard builder.setSingleChoiceItems(R.array.sort_types_array, currentIndex.get(), (dialog, which) -> currentIndex.set(which)); builder.setPositiveButton(R.string.sort, (dialog, which) -> { - if(ch.isChecked()) { + if (ch.isChecked()) { setSort(loyaltyCardOrders.get(currentIndex.get()), DBHelper.LoyaltyCardOrderDirection.Descending); - } - else { + } else { setSort(loyaltyCardOrders.get(currentIndex.get()), DBHelper.LoyaltyCardOrderDirection.Ascending); } dialog.dismiss(); @@ -553,29 +524,25 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard return true; } - if (id == R.id.action_manage_groups) - { + if (id == R.id.action_manage_groups) { Intent i = new Intent(getApplicationContext(), ManageGroupsActivity.class); startActivityForResult(i, Utils.MAIN_REQUEST); return true; } - if (id == R.id.action_import_export) - { + if (id == R.id.action_import_export) { Intent i = new Intent(getApplicationContext(), ImportExportActivity.class); startActivityForResult(i, Utils.MAIN_REQUEST); return true; } - if (id == R.id.action_settings) - { + if (id == R.id.action_settings) { Intent i = new Intent(getApplicationContext(), SettingsActivity.class); startActivityForResult(i, Utils.MAIN_REQUEST); return true; } - if (id == R.id.action_about) - { + if (id == R.id.action_about) { Intent i = new Intent(getApplicationContext(), AboutActivity.class); startActivityForResult(i, Utils.MAIN_REQUEST); return true; @@ -648,10 +615,10 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } Integer currentTab = groupsTabLayout.getSelectedTabPosition(); - Log.d("onFling","Current Tab "+currentTab); + Log.d("onFling", "Current Tab " + currentTab); // Swipe right if (velocityX < -150) { - Log.d("onFling","Right Swipe detected "+velocityX); + Log.d("onFling", "Right Swipe detected " + velocityX); Integer nextTab = currentTab + 1; if (nextTab == groupsTabLayout.getTabCount()) { @@ -665,7 +632,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard // Swipe left if (velocityX > 150) { - Log.d("onFling","Left Swipe detected "+velocityX); + Log.d("onFling", "Left Swipe detected " + velocityX); Integer nextTab = currentTab - 1; if (nextTab < 0) { @@ -681,22 +648,18 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard } @Override - public void onRowLongClicked(int inputPosition) - { + public void onRowLongClicked(int inputPosition) { enableActionMode(inputPosition); } - private void enableActionMode(int inputPosition) - { - if (mCurrentActionMode == null) - { + private void enableActionMode(int inputPosition) { + if (mCurrentActionMode == null) { mCurrentActionMode = startSupportActionMode(mCurrentActionModeCallback); } toggleSelection(inputPosition); } - private void toggleSelection(int inputPosition) - { + private void toggleSelection(int inputPosition) { mAdapter.toggleSelection(inputPosition); int count = mAdapter.getSelectedItemCount(); @@ -720,14 +683,10 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard @Override - public void onRowClicked(int inputPosition) - { - if (mAdapter.getSelectedItemCount() > 0) - { + public void onRowClicked(int inputPosition) { + if (mAdapter.getSelectedItemCount() > 0) { enableActionMode(inputPosition); - } - else - { + } else { Cursor selected = mAdapter.getCursor(); selected.moveToPosition(inputPosition); // FIXME diff --git a/app/src/main/java/protect/card_locker/ManageGroupActivity.java b/app/src/main/java/protect/card_locker/ManageGroupActivity.java index ec3c2ccb8..8e0df0883 100644 --- a/app/src/main/java/protect/card_locker/ManageGroupActivity.java +++ b/app/src/main/java/protect/card_locker/ManageGroupActivity.java @@ -2,7 +2,6 @@ package protect.card_locker; import android.content.Intent; - import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; @@ -24,8 +23,7 @@ import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.RecyclerView; -public class ManageGroupActivity extends CatimaAppCompatActivity implements ManageGroupCursorAdapter.CardAdapterListener -{ +public class ManageGroupActivity extends CatimaAppCompatActivity implements ManageGroupCursorAdapter.CardAdapterListener { private final DBHelper mDB = new DBHelper(this); private ManageGroupCursorAdapter mAdapter; @@ -41,8 +39,7 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana private boolean mGroupNameNotInUse; @Override - protected void onCreate(Bundle inputSavedInstanceState) - { + protected void onCreate(Bundle inputSavedInstanceState) { super.onCreate(inputSavedInstanceState); setContentView(R.layout.activity_manage_group); Toolbar toolbar = findViewById(R.id.toolbar); @@ -68,7 +65,7 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana mGroupNameNotInUse = true; mGroupNameText.setError(null); String currentGroupName = mGroupNameText.getText().toString().trim(); - if(currentGroupName.length() == 0){ + if (currentGroupName.length() == 0) { mGroupNameText.setError(getResources().getText(R.string.group_name_is_empty)); return; } @@ -85,13 +82,13 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana Intent intent = getIntent(); String groupId = intent.getStringExtra("group"); - if (groupId == null){ - throw(new IllegalArgumentException("this activity expects a group loaded into it's intent")); + if (groupId == null) { + throw (new IllegalArgumentException("this activity expects a group loaded into it's intent")); } Log.d("groupId", "groupId: " + groupId); mGroup = mDB.getGroup(groupId); - if (mGroup == null){ - throw(new IllegalArgumentException("cannot load group " + groupId + " from database")); + if (mGroup == null) { + throw (new IllegalArgumentException("cannot load group " + groupId + " from database")); } mGroupNameText.setText(mGroup._id); setTitle(getString(R.string.editGroup, mGroup._id)); @@ -105,27 +102,27 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana } ActionBar actionBar = getSupportActionBar(); - if (actionBar == null){ - throw(new RuntimeException("mActionBar is not expected to be null here")); + if (actionBar == null) { + throw (new RuntimeException("mActionBar is not expected to be null here")); } actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); saveButton.setOnClickListener(v -> { String currentGroupName = mGroupNameText.getText().toString().trim(); - if(!currentGroupName.equals(mGroup._id)){ - if(currentGroupName.length() == 0){ + if (!currentGroupName.equals(mGroup._id)) { + if (currentGroupName.length() == 0) { Toast.makeText(getApplicationContext(), R.string.group_name_is_empty, Toast.LENGTH_SHORT).show(); return; } - if(!mGroupNameNotInUse) { + if (!mGroupNameNotInUse) { Toast.makeText(getApplicationContext(), R.string.group_name_already_in_use, Toast.LENGTH_SHORT).show(); return; } } mAdapter.commitToDatabase(); - if(!currentGroupName.equals(mGroup._id)){ + if (!currentGroupName.equals(mGroup._id)) { mDB.updateGroup(mGroup._id, currentGroupName); } Toast.makeText(getApplicationContext(), R.string.group_updated, Toast.LENGTH_SHORT).show(); @@ -136,29 +133,29 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana updateLoyaltyCardList(); } - private ArrayList adapterStateToIntegerArray(HashMap adapterState){ + private ArrayList adapterStateToIntegerArray(HashMap adapterState) { ArrayList ret = new ArrayList<>(adapterState.size() * 2); for (Map.Entry entry : adapterState.entrySet()) { ret.add(entry.getKey()); - ret.add(entry.getValue()?1:0); + ret.add(entry.getValue() ? 1 : 0); } return ret; } private HashMap integerArrayToAdapterState(ArrayList in) { HashMap ret = new HashMap<>(); - if (in.size() % 2 != 0){ - throw(new RuntimeException("failed restoring adapterState from integer array list")); + if (in.size() % 2 != 0) { + throw (new RuntimeException("failed restoring adapterState from integer array list")); } - for(int i = 0;i < in.size(); i += 2){ - ret.put(in.get(i), in.get(i+1) == 1); + for (int i = 0; i < in.size(); i += 2) { + ret.put(in.get(i), in.get(i + 1) == 1); } return ret; } @Override - protected void onSaveInstanceState (@NonNull Bundle outState){ + protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putIntegerArrayList(SAVE_INSTANCE_ADAPTER_STATE, adapterStateToIntegerArray(mAdapter.exportInGroupState())); @@ -168,18 +165,17 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana private void updateLoyaltyCardList() { mAdapter.swapCursor(mDB.getLoyaltyCardCursor()); - if(mAdapter.getCountFromCursor() == 0) - { + if (mAdapter.getCountFromCursor() == 0) { mCardList.setVisibility(View.GONE); mHelpText.setVisibility(View.VISIBLE); - }else { + } else { mCardList.setVisibility(View.VISIBLE); mHelpText.setVisibility(View.GONE); } } - private void leaveWithoutSaving(){ - if (hasChanged()){ + private void leaveWithoutSaving() { + if (hasChanged()) { AlertDialog.Builder builder = new AlertDialog.Builder(ManageGroupActivity.this); builder.setTitle(R.string.leaveWithoutSaveTitle); builder.setMessage(R.string.leaveWithoutSaveConfirmation); @@ -187,36 +183,33 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()); AlertDialog dialog = builder.create(); dialog.show(); - }else{ + } else { finish(); } } @Override - public void onBackPressed() - { + public void onBackPressed() { leaveWithoutSaving(); } - + @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } - private boolean hasChanged(){ + private boolean hasChanged() { return mAdapter.hasChanged() || !mGroup._id.equals(mGroupNameText.getText().toString().trim()); } @Override - public void onRowLongClicked(int inputPosition) - { + public void onRowLongClicked(int inputPosition) { // do nothing for now } @Override - public void onRowClicked(int inputPosition) - { + public void onRowClicked(int inputPosition) { mAdapter.toggleSelection(inputPosition); } diff --git a/app/src/main/java/protect/card_locker/ManageGroupCursorAdapter.java b/app/src/main/java/protect/card_locker/ManageGroupCursorAdapter.java index 96f62fdfa..cef4fb8d1 100644 --- a/app/src/main/java/protect/card_locker/ManageGroupCursorAdapter.java +++ b/app/src/main/java/protect/card_locker/ManageGroupCursorAdapter.java @@ -14,7 +14,8 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter { private HashMap> mGetGroupCache; final private Group mGroup; final private DBHelper mDb; - public ManageGroupCursorAdapter(Context inputContext, Cursor inputCursor, CardAdapterListener inputListener, Group group){ + + public ManageGroupCursorAdapter(Context inputContext, Cursor inputCursor, CardAdapterListener inputListener, Group group) { super(inputContext, inputCursor, inputListener); mGroup = new Group(group._id, group.order); mInGroupOverlay = new HashMap<>(); @@ -30,10 +31,10 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter { } @Override - public void onBindViewHolder(LoyaltyCardListItemViewHolder inputHolder, Cursor inputCursor){ + public void onBindViewHolder(LoyaltyCardListItemViewHolder inputHolder, Cursor inputCursor) { LoyaltyCard loyaltyCard = LoyaltyCard.toLoyaltyCard(inputCursor); Boolean overlayValue = mInGroupOverlay.get(loyaltyCard.id); - if((overlayValue != null? overlayValue: isLoyaltyCardInGroup(loyaltyCard.id))) { + if ((overlayValue != null ? overlayValue : isLoyaltyCardInGroup(loyaltyCard.id))) { mAnimationItemsIndex.put(inputCursor.getPosition(), true); mSelectedItems.put(inputCursor.getPosition(), true); } @@ -41,9 +42,9 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter { super.onBindViewHolder(inputHolder, inputCursor); } - private List getGroups(int cardId){ + private List getGroups(int cardId) { List cache = mGetGroupCache.get(cardId); - if(cache != null){ + if (cache != null) { return cache; } List groups = mDb.getLoyaltyCardGroups(cardId); @@ -51,13 +52,13 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter { return groups; } - private boolean isLoyaltyCardInGroup(int cardId){ + private boolean isLoyaltyCardInGroup(int cardId) { Boolean cache = mIsLoyaltyCardInGroupCache.get(cardId); - if(cache != null){ + if (cache != null) { return cache; } List groups = getGroups(cardId); - if (groups.contains(mGroup)){ + if (groups.contains(mGroup)) { mIsLoyaltyCardInGroupCache.put(cardId, true); return true; } @@ -66,16 +67,16 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter { } @Override - public void toggleSelection(int inputPosition){ + public void toggleSelection(int inputPosition) { super.toggleSelection(inputPosition); Integer cardId = mIndexCardMap.get(inputPosition); - if (cardId == null){ - throw(new RuntimeException("cardId should not be null here")); + if (cardId == null) { + throw (new RuntimeException("cardId should not be null here")); } Boolean overlayValue = mInGroupOverlay.get(cardId); - if (overlayValue == null){ + if (overlayValue == null) { mInGroupOverlay.put(cardId, !isLoyaltyCardInGroup(cardId)); - }else{ + } else { mInGroupOverlay.remove(cardId); } } @@ -84,13 +85,13 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter { return mInGroupOverlay.size() > 0; } - public void commitToDatabase(){ - for(Map.Entry entry: mInGroupOverlay.entrySet()){ + public void commitToDatabase() { + for (Map.Entry entry : mInGroupOverlay.entrySet()) { int cardId = entry.getKey(); List groups = getGroups(cardId); - if(entry.getValue()){ + if (entry.getValue()) { groups.add(mGroup); - }else{ + } else { groups.remove(mGroup); } mDb.setLoyaltyCardGroups(cardId, groups); @@ -101,7 +102,7 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter { mInGroupOverlay = new HashMap<>(cardIdInGroupMap); } - public HashMap exportInGroupState(){ + public HashMap exportInGroupState() { return new HashMap<>(mInGroupOverlay); } diff --git a/app/src/main/java/protect/card_locker/ManageGroupsActivity.java b/app/src/main/java/protect/card_locker/ManageGroupsActivity.java index 116dc7a1c..2573a9440 100644 --- a/app/src/main/java/protect/card_locker/ManageGroupsActivity.java +++ b/app/src/main/java/protect/card_locker/ManageGroupsActivity.java @@ -23,8 +23,7 @@ import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -public class ManageGroupsActivity extends CatimaAppCompatActivity implements GroupCursorAdapter.GroupAdapterListener -{ +public class ManageGroupsActivity extends CatimaAppCompatActivity implements GroupCursorAdapter.GroupAdapterListener { private static final String TAG = "Catima"; private final DBHelper mDb = new DBHelper(this); @@ -33,16 +32,14 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro GroupCursorAdapter mAdapter; @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.groups); setContentView(R.layout.manage_groups_activity); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); - if(actionBar != null) - { + if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } @@ -74,8 +71,7 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro super.onBackPressed(); } - private void updateGroupList() - { + private void updateGroupList() { mAdapter.swapCursor(mDb.getGroupCursor()); if (mDb.getGroupCount() == 0) { @@ -89,8 +85,7 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro mHelpText.setVisibility(View.GONE); } - private void invalidateHomescreenActiveTab() - { + private void invalidateHomescreenActiveTab() { SharedPreferences activeTabPref = getApplicationContext().getSharedPreferences( getString(R.string.sharedpreference_active_tab), Context.MODE_PRIVATE); @@ -100,8 +95,7 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro } @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { @@ -112,7 +106,7 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro } private void createGroup() { - AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AlertDialogTheme); + AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme); builder.setTitle(R.string.enter_group_name); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_TEXT); @@ -120,7 +114,7 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro builder.setPositiveButton(getString(R.string.ok), (dialog, which) -> { String inputString = input.getText().toString().trim(); - if(inputString.length() == 0){ + if (inputString.length() == 0) { Toast.makeText(getApplicationContext(), R.string.group_name_is_empty, Toast.LENGTH_SHORT).show(); return; } diff --git a/app/src/main/java/protect/card_locker/ScanActivity.java b/app/src/main/java/protect/card_locker/ScanActivity.java index 826263c86..a69daac5e 100644 --- a/app/src/main/java/protect/card_locker/ScanActivity.java +++ b/app/src/main/java/protect/card_locker/ScanActivity.java @@ -25,7 +25,7 @@ import androidx.appcompat.widget.Toolbar; /** * Custom Scannner Activity extending from Activity to display a custom layout form scanner view. - * + *

* Based on https://github.com/journeyapps/zxing-android-embedded/blob/0fdfbce9fb3285e985bad9971c5f7c0a7a334e7b/sample/src/main/java/example/zxing/CustomScannerActivity.java * originally licensed under Apache 2.0 */ @@ -54,8 +54,7 @@ public class ScanActivity extends CatimaAppCompatActivity { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); - if(actionBar != null) - { + if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } @@ -127,8 +126,7 @@ public class ScanActivity extends CatimaAppCompatActivity { } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) { getMenuInflater().inflate(R.menu.scan_menu, menu); } @@ -139,10 +137,8 @@ public class ScanActivity extends CatimaAppCompatActivity { } @Override - public boolean onOptionsItemSelected(MenuItem item) - { - if (item.getItemId() == android.R.id.home) - { + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == android.R.id.home) { setResult(Activity.RESULT_CANCELED); finish(); return true; @@ -164,8 +160,7 @@ public class ScanActivity extends CatimaAppCompatActivity { } @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) - { + public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); BarcodeValues barcodeValues; diff --git a/app/src/main/java/protect/card_locker/ShortcutHelper.java b/app/src/main/java/protect/card_locker/ShortcutHelper.java index 29bbff461..8c3ae2e53 100644 --- a/app/src/main/java/protect/card_locker/ShortcutHelper.java +++ b/app/src/main/java/protect/card_locker/ShortcutHelper.java @@ -14,8 +14,7 @@ import androidx.core.content.pm.ShortcutInfoCompat; import androidx.core.content.pm.ShortcutManagerCompat; import androidx.core.graphics.drawable.IconCompat; -class ShortcutHelper -{ +class ShortcutHelper { // Android documentation says that no more than 5 shortcuts // are supported. However, that may be too many, as not all // launcher will show all 5. Instead, the number is limited @@ -30,8 +29,7 @@ class ShortcutHelper * card exceeds the max number of shortcuts, then the least recently * used card shortcut is discarded. */ - static void updateShortcuts(Context context, LoyaltyCard card) - { + static void updateShortcuts(Context context, LoyaltyCard card) { LinkedList list = new LinkedList<>(ShortcutManagerCompat.getDynamicShortcuts(context)); DBHelper dbHelper = new DBHelper(context); @@ -44,31 +42,25 @@ class ShortcutHelper Integer foundIndex = null; - for(int index = 0; index < list.size(); index++) - { - if(list.get(index).getId().equals(shortcutId)) - { + for (int index = 0; index < list.size(); index++) { + if (list.get(index).getId().equals(shortcutId)) { // Found the item already foundIndex = index; break; } } - if(foundIndex != null) - { + if (foundIndex != null) { // If the item is already found, then the list needs to be // reordered, so that the selected item now has the lowest // rank, thus letting it survive longer. ShortcutInfoCompat found = list.remove(foundIndex.intValue()); list.addFirst(found); - } - else - { + } else { // The item is new to the list. First, we need to trim the list // until it is able to accept a new item, then the item is // inserted. - while(list.size() >= MAX_SHORTCUTS) - { + while (list.size() >= MAX_SHORTCUTS) { list.pollLast(); } @@ -80,15 +72,14 @@ class ShortcutHelper LinkedList finalList = new LinkedList<>(); // The ranks are now updated; the order in the list is the rank. - for(int index = 0; index < list.size(); index++) - { + for (int index = 0; index < list.size(); index++) { ShortcutInfoCompat prevShortcut = list.get(index); LoyaltyCard loyaltyCard = dbHelper.getLoyaltyCard(Integer.parseInt(prevShortcut.getId())); ShortcutInfoCompat updatedShortcut = createShortcutBuilder(context, loyaltyCard) - .setRank(index) - .build(); + .setRank(index) + .build(); finalList.addLast(updatedShortcut); } @@ -100,16 +91,13 @@ class ShortcutHelper * Remove the given card id from the app shortcuts, if such a * shortcut exists. */ - static void removeShortcut(Context context, int cardId) - { + static void removeShortcut(Context context, int cardId) { List list = ShortcutManagerCompat.getDynamicShortcuts(context); String shortcutId = Integer.toString(cardId); - for(int index = 0; index < list.size(); index++) - { - if(list.get(index).getId().equals(shortcutId)) - { + for (int index = 0; index < list.size(); index++) { + if (list.get(index).getId().equals(shortcutId)) { list.remove(index); break; } diff --git a/app/src/main/java/protect/card_locker/SimpleTextWatcher.java b/app/src/main/java/protect/card_locker/SimpleTextWatcher.java index d6483b4a8..05c9762e3 100644 --- a/app/src/main/java/protect/card_locker/SimpleTextWatcher.java +++ b/app/src/main/java/protect/card_locker/SimpleTextWatcher.java @@ -5,11 +5,14 @@ import android.text.TextWatcher; public class SimpleTextWatcher implements TextWatcher { @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { } + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { } + public void onTextChanged(CharSequence s, int start, int before, int count) { + } @Override - public void afterTextChanged(Editable s) { } + public void afterTextChanged(Editable s) { + } } diff --git a/app/src/main/java/protect/card_locker/Utils.java b/app/src/main/java/protect/card_locker/Utils.java index eb889b479..51fb34fa0 100644 --- a/app/src/main/java/protect/card_locker/Utils.java +++ b/app/src/main/java/protect/card_locker/Utils.java @@ -361,7 +361,7 @@ public class Utils { return retrieveCardImage(context, getCardImageFileName(loyaltyCardId, front)); } - static public U mapGetOrDefault(Map map, T key, U defaultValue) { + static public U mapGetOrDefault(Map map, T key, U defaultValue) { U value = map.get(key); if (value == null) { return defaultValue; @@ -404,43 +404,42 @@ public class Utils { return System.currentTimeMillis() / 1000; } - static public boolean isDarkModeEnabled(Context inputContext) - { + static public boolean isDarkModeEnabled(Context inputContext) { int nightModeSetting = new Settings(inputContext).getTheme(); if (nightModeSetting == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) { Configuration config = inputContext.getResources().getConfiguration(); int currentNightMode = config.uiMode & Configuration.UI_MODE_NIGHT_MASK; return (currentNightMode == Configuration.UI_MODE_NIGHT_YES); - }else { + } else { return nightModeSetting == AppCompatDelegate.MODE_NIGHT_YES; } } - public static File createTempFile(Context context, String name){ + public static File createTempFile(Context context, String name) { return new File(context.getCacheDir() + "/" + name); } - public static String saveTempImage(Context context, Bitmap in, String name, Bitmap.CompressFormat format){ + public static String saveTempImage(Context context, Bitmap in, String name, Bitmap.CompressFormat format) { File image = createTempFile(context, name); - try (FileOutputStream out = new FileOutputStream(image)){ + try (FileOutputStream out = new FileOutputStream(image)) { in.compress(format, 100, out); return image.getAbsolutePath(); - }catch(IOException e){ + } catch (IOException e) { Log.d("store temp image", "failed writing temp file for temporary image, name: " + name); return null; } } - public static Bitmap loadImage(String path){ - try{ + public static Bitmap loadImage(String path) { + try { return BitmapFactory.decodeStream(new FileInputStream(path)); - }catch(IOException e){ + } catch (IOException e) { Log.d("load image", "failed loading image from " + path); return null; } } - public static Bitmap loadTempImage(Context context, String name){ + public static Bitmap loadTempImage(Context context, String name) { return loadImage(context.getCacheDir() + "/" + name); } diff --git a/app/src/main/java/protect/card_locker/async/CompatCallable.java b/app/src/main/java/protect/card_locker/async/CompatCallable.java index e58d15c2c..352e0aeac 100644 --- a/app/src/main/java/protect/card_locker/async/CompatCallable.java +++ b/app/src/main/java/protect/card_locker/async/CompatCallable.java @@ -4,5 +4,6 @@ import java.util.concurrent.Callable; public interface CompatCallable extends Callable { void onPostExecute(Object result); + void onPreExecute(); } diff --git a/app/src/main/java/protect/card_locker/async/TaskHandler.java b/app/src/main/java/protect/card_locker/async/TaskHandler.java index c25b13e33..c417704be 100644 --- a/app/src/main/java/protect/card_locker/async/TaskHandler.java +++ b/app/src/main/java/protect/card_locker/async/TaskHandler.java @@ -13,11 +13,11 @@ import java.util.concurrent.TimeUnit; /** * AsyncTask has been deprecated so this provides very rudimentary compatibility without * needing to redo too many Parts. - * + *

* However this is a much, much more cooperative Behaviour than before so * the callers need to ensure we do NOT rely on forced cancellation and feed less into the * ThreadPools so we don't OOM/Overload the Users device - * + *

* This assumes single-threaded callers. */ public class TaskHandler { @@ -44,9 +44,10 @@ public class TaskHandler { /** * Replaces (or initializes) an Executor with a clean (new) one + * * @param executors Map Reference - * @param type Which Queue - * @param flushOld attempt shutdown + * @param type Which Queue + * @param flushOld attempt shutdown * @param waitOnOld wait for Termination */ private void replaceExecutor(HashMap executors, TYPE type, Boolean flushOld, Boolean waitOnOld) { diff --git a/app/src/main/java/protect/card_locker/importexport/CSVHelpers.java b/app/src/main/java/protect/card_locker/importexport/CSVHelpers.java index 74dd8f94e..d21b0f11a 100644 --- a/app/src/main/java/protect/card_locker/importexport/CSVHelpers.java +++ b/app/src/main/java/protect/card_locker/importexport/CSVHelpers.java @@ -12,18 +12,13 @@ public class CSVHelpers { * if it is not null. Otherwise, a FormatException is thrown. */ static String extractString(String key, CSVRecord record, String defaultValue) - throws FormatException - { + throws FormatException { String toReturn = defaultValue; - if(record.isMapped(key)) - { + if (record.isMapped(key)) { toReturn = record.get(key); - } - else - { - if(defaultValue == null) - { + } else { + if (defaultValue == null) { throw new FormatException("Field not used but expected: " + key); } } @@ -38,25 +33,19 @@ public class CSVHelpers { * int, a FormatException is thrown. */ static Integer extractInt(String key, CSVRecord record, boolean nullIsOk) - throws FormatException - { - if(record.isMapped(key) == false) - { + throws FormatException { + if (record.isMapped(key) == false) { throw new FormatException("Field not used but expected: " + key); } String value = record.get(key); - if(value.isEmpty() && nullIsOk) - { + if (value.isEmpty() && nullIsOk) { return null; } - try - { + try { return Integer.parseInt(record.get(key)); - } - catch(NumberFormatException e) - { + } catch (NumberFormatException e) { throw new FormatException("Failed to parse field: " + key, e); } } @@ -68,25 +57,19 @@ public class CSVHelpers { * int, a FormatException is thrown. */ static Long extractLong(String key, CSVRecord record, boolean nullIsOk) - throws FormatException - { - if(record.isMapped(key) == false) - { + throws FormatException { + if (record.isMapped(key) == false) { throw new FormatException("Field not used but expected: " + key); } String value = record.get(key); - if(value.isEmpty() && nullIsOk) - { + if (value.isEmpty() && nullIsOk) { return null; } - try - { + try { return Long.parseLong(record.get(key)); - } - catch(NumberFormatException e) - { + } catch (NumberFormatException e) { throw new FormatException("Failed to parse field: " + key, e); } } diff --git a/app/src/main/java/protect/card_locker/importexport/CatimaExporter.java b/app/src/main/java/protect/card_locker/importexport/CatimaExporter.java index 119443bba..060a93e50 100644 --- a/app/src/main/java/protect/card_locker/importexport/CatimaExporter.java +++ b/app/src/main/java/protect/card_locker/importexport/CatimaExporter.java @@ -29,10 +29,8 @@ import protect.card_locker.Utils; * Class for exporting the database into CSV (Comma Separate Values) * format. */ -public class CatimaExporter implements Exporter -{ - public void exportData(Context context, DBHelper db, OutputStream output,char[] password) throws IOException, InterruptedException - { +public class CatimaExporter implements Exporter { + public void exportData(Context context, DBHelper db, OutputStream output, char[] password) throws IOException, InterruptedException { // Necessary vars int readLen; byte[] readBuffer = new byte[InternalZipConstants.BUFF_SIZE]; @@ -40,10 +38,9 @@ public class CatimaExporter implements Exporter // Create zip output stream ZipOutputStream zipOutputStream; - if(password!=null && password.length>0){ - zipOutputStream = new ZipOutputStream(output,password); - } - else{ + if (password != null && password.length > 0) { + zipOutputStream = new ZipOutputStream(output, password); + } else { zipOutputStream = new ZipOutputStream(output); } @@ -53,7 +50,7 @@ public class CatimaExporter implements Exporter writeCSV(db, catimaOutputStreamWriter); // Add CSV to zip file - ZipParameters csvZipParameters = createZipParameters("catima.csv",password); + ZipParameters csvZipParameters = createZipParameters("catima.csv", password); zipOutputStream.putNextEntry(csvZipParameters); InputStream csvInputStream = new ByteArrayInputStream(catimaOutputStream.toByteArray()); while ((readLen = csvInputStream.read(readBuffer)) != -1) { @@ -63,8 +60,7 @@ public class CatimaExporter implements Exporter // Loop over all cards again Cursor cardCursor = db.getLoyaltyCardCursor(); - while(cardCursor.moveToNext()) - { + while (cardCursor.moveToNext()) { // For each card LoyaltyCard card = LoyaltyCard.toLoyaltyCard(cardCursor); @@ -78,7 +74,7 @@ public class CatimaExporter implements Exporter // If it exists, add to the .zip file Bitmap image = Utils.retrieveCardImage(context, card.id, front); if (image != null) { - ZipParameters imageZipParameters = createZipParameters(Utils.getCardImageFileName(card.id, front),password); + ZipParameters imageZipParameters = createZipParameters(Utils.getCardImageFileName(card.id, front), password); zipOutputStream.putNextEntry(imageZipParameters); InputStream imageInputStream = new ByteArrayInputStream(Utils.bitmapToByteArray(image)); while ((readLen = imageInputStream.read(readBuffer)) != -1) { @@ -92,10 +88,10 @@ public class CatimaExporter implements Exporter zipOutputStream.close(); } - private ZipParameters createZipParameters(String fileName, char[] password){ + private ZipParameters createZipParameters(String fileName, char[] password) { ZipParameters zipParameters = new ZipParameters(); zipParameters.setFileNameInZip(fileName); - if(password!=null && password.length>0){ + if (password != null && password.length > 0) { zipParameters.setEncryptFiles(true); zipParameters.setEncryptionMethod(EncryptionMethod.AES); } @@ -115,14 +111,12 @@ public class CatimaExporter implements Exporter Cursor groupCursor = db.getGroupCursor(); - while(groupCursor.moveToNext()) - { + while (groupCursor.moveToNext()) { Group group = Group.toGroup(groupCursor); printer.printRecord(group._id); - if(Thread.currentThread().isInterrupted()) - { + if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } } @@ -148,8 +142,7 @@ public class CatimaExporter implements Exporter Cursor cardCursor = db.getLoyaltyCardCursor(); - while(cardCursor.moveToNext()) - { + while (cardCursor.moveToNext()) { LoyaltyCard card = LoyaltyCard.toLoyaltyCard(cardCursor); printer.printRecord(card.id, @@ -165,8 +158,7 @@ public class CatimaExporter implements Exporter card.starStatus, card.lastUsed); - if(Thread.currentThread().isInterrupted()) - { + if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } } @@ -182,16 +174,14 @@ public class CatimaExporter implements Exporter Cursor cardCursor2 = db.getLoyaltyCardCursor(); - while(cardCursor2.moveToNext()) - { + while (cardCursor2.moveToNext()) { LoyaltyCard card = LoyaltyCard.toLoyaltyCard(cardCursor2); for (Group group : db.getLoyaltyCardGroups(card.id)) { printer.printRecord(card.id, group._id); } - if(Thread.currentThread().isInterrupted()) - { + if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } } diff --git a/app/src/main/java/protect/card_locker/importexport/CatimaImporter.java b/app/src/main/java/protect/card_locker/importexport/CatimaImporter.java index 2ea858e1f..6b4fc05a5 100644 --- a/app/src/main/java/protect/card_locker/importexport/CatimaImporter.java +++ b/app/src/main/java/protect/card_locker/importexport/CatimaImporter.java @@ -4,8 +4,6 @@ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; -import com.google.zxing.BarcodeFormat; - import net.lingala.zip4j.io.inputstream.ZipInputStream; import net.lingala.zip4j.model.LocalFileHeader; @@ -37,18 +35,17 @@ import protect.card_locker.ZipUtils; /** * Class for importing a database from CSV (Comma Separate Values) * formatted data. - * + *

* The database's loyalty cards are expected to appear in the CSV data. * A header is expected for the each table showing the names of the columns. */ -public class CatimaImporter implements Importer -{ +public class CatimaImporter implements Importer { public void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, InterruptedException { InputStream bufferedInputStream = new BufferedInputStream(input); bufferedInputStream.mark(100); // First, check if this is a zip file - ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream,password); + ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream, password); boolean isZipFile = false; @@ -102,41 +99,32 @@ public class CatimaImporter implements Importer bufferedReader.close(); } - public void parseV1(Context context, DBHelper db, BufferedReader input) throws IOException, FormatException, InterruptedException - { + public void parseV1(Context context, DBHelper db, BufferedReader input) throws IOException, FormatException, InterruptedException { final CSVParser parser = new CSVParser(input, CSVFormat.RFC4180.builder().setHeader().build()); SQLiteDatabase database = db.getWritableDatabase(); database.beginTransaction(); - try - { - for (CSVRecord record : parser) - { + try { + for (CSVRecord record : parser) { importLoyaltyCard(context, database, db, record); - if(Thread.currentThread().isInterrupted()) - { + if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } } parser.close(); database.setTransactionSuccessful(); - } - catch(IllegalArgumentException|IllegalStateException e) - { + } catch (IllegalArgumentException | IllegalStateException e) { throw new FormatException("Issue parsing CSV data", e); - } - finally - { + } finally { database.endTransaction(); database.close(); } } - public void parseV2(Context context, DBHelper db, BufferedReader input) throws IOException, FormatException, InterruptedException - { + public void parseV2(Context context, DBHelper db, BufferedReader input) throws IOException, FormatException, InterruptedException { SQLiteDatabase database = db.getWritableDatabase(); database.beginTransaction(); @@ -206,8 +194,7 @@ public class CatimaImporter implements Importer } } - public void parseV2Groups(DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException - { + public void parseV2Groups(DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException { // Parse groups final CSVParser groupParser = new CSVParser(new StringReader(data), CSVFormat.RFC4180.builder().setHeader().build()); @@ -232,8 +219,7 @@ public class CatimaImporter implements Importer } } - public void parseV2Cards(Context context, DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException - { + public void parseV2Cards(Context context, DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException { // Parse cards final CSVParser cardParser = new CSVParser(new StringReader(data), CSVFormat.RFC4180.builder().setHeader().build()); @@ -258,8 +244,7 @@ public class CatimaImporter implements Importer } } - public void parseV2CardGroups(DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException - { + public void parseV2CardGroups(DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException { // Parse card group mappings final CSVParser cardGroupParser = new CSVParser(new StringReader(data), CSVFormat.RFC4180.builder().setHeader().build()); @@ -289,13 +274,11 @@ public class CatimaImporter implements Importer * session. */ private void importLoyaltyCard(Context context, SQLiteDatabase database, DBHelper helper, CSVRecord record) - throws IOException, FormatException - { + throws IOException, FormatException { int id = CSVHelpers.extractInt(DBHelper.LoyaltyCardDbIds.ID, record, false); String store = CSVHelpers.extractString(DBHelper.LoyaltyCardDbIds.STORE, record, ""); - if(store.isEmpty()) - { + if (store.isEmpty()) { throw new FormatException("No store listed, but is required"); } @@ -303,12 +286,13 @@ public class CatimaImporter implements Importer Date expiry = null; try { expiry = new Date(CSVHelpers.extractLong(DBHelper.LoyaltyCardDbIds.EXPIRY, record, true)); - } catch (NullPointerException | FormatException e) { } + } catch (NullPointerException | FormatException e) { + } BigDecimal balance; try { balance = new BigDecimal(CSVHelpers.extractString(DBHelper.LoyaltyCardDbIds.BALANCE, record, null)); - } catch (FormatException _e ) { + } catch (FormatException _e) { // These fields did not exist in versions 1.8.1 and before // We catch this exception so we can still import old backups balance = new BigDecimal("0"); @@ -316,33 +300,29 @@ public class CatimaImporter implements Importer Currency balanceType = null; String unparsedBalanceType = CSVHelpers.extractString(DBHelper.LoyaltyCardDbIds.BALANCE_TYPE, record, ""); - if(!unparsedBalanceType.isEmpty()) { + if (!unparsedBalanceType.isEmpty()) { balanceType = Currency.getInstance(unparsedBalanceType); } String cardId = CSVHelpers.extractString(DBHelper.LoyaltyCardDbIds.CARD_ID, record, ""); - if(cardId.isEmpty()) - { + if (cardId.isEmpty()) { throw new FormatException("No card ID listed, but is required"); } String barcodeId = CSVHelpers.extractString(DBHelper.LoyaltyCardDbIds.BARCODE_ID, record, ""); - if(barcodeId.isEmpty()) - { + if (barcodeId.isEmpty()) { barcodeId = null; } CatimaBarcode barcodeType = null; String unparsedBarcodeType = CSVHelpers.extractString(DBHelper.LoyaltyCardDbIds.BARCODE_TYPE, record, ""); - if(!unparsedBarcodeType.isEmpty()) - { + if (!unparsedBarcodeType.isEmpty()) { barcodeType = CatimaBarcode.fromName(unparsedBarcodeType); } Integer headerColor = null; - if(record.isMapped(DBHelper.LoyaltyCardDbIds.HEADER_COLOR)) - { + if (record.isMapped(DBHelper.LoyaltyCardDbIds.HEADER_COLOR)) { headerColor = CSVHelpers.extractInt(DBHelper.LoyaltyCardDbIds.HEADER_COLOR, record, true); } @@ -371,8 +351,7 @@ public class CatimaImporter implements Importer * session. */ private void importGroup(SQLiteDatabase database, DBHelper helper, CSVRecord record) - throws IOException, FormatException - { + throws IOException, FormatException { String id = CSVHelpers.extractString(DBHelper.LoyaltyCardDbGroups.ID, record, null); helper.insertGroup(database, id); @@ -383,8 +362,7 @@ public class CatimaImporter implements Importer * session. */ private void importCardGroupMapping(SQLiteDatabase database, DBHelper helper, CSVRecord record) - throws IOException, FormatException - { + throws IOException, FormatException { Integer cardId = CSVHelpers.extractInt(DBHelper.LoyaltyCardDbIdsGroups.cardID, record, false); String groupId = CSVHelpers.extractString(DBHelper.LoyaltyCardDbIdsGroups.groupID, record, null); diff --git a/app/src/main/java/protect/card_locker/importexport/DataFormat.java b/app/src/main/java/protect/card_locker/importexport/DataFormat.java index 26e97e745..fc4fdc531 100644 --- a/app/src/main/java/protect/card_locker/importexport/DataFormat.java +++ b/app/src/main/java/protect/card_locker/importexport/DataFormat.java @@ -1,10 +1,8 @@ package protect.card_locker.importexport; -public enum DataFormat -{ +public enum DataFormat { Catima, Fidme, Stocard, - VoucherVault - ; + VoucherVault; } diff --git a/app/src/main/java/protect/card_locker/importexport/Exporter.java b/app/src/main/java/protect/card_locker/importexport/Exporter.java index ad4928030..584572360 100644 --- a/app/src/main/java/protect/card_locker/importexport/Exporter.java +++ b/app/src/main/java/protect/card_locker/importexport/Exporter.java @@ -11,11 +11,11 @@ import protect.card_locker.DBHelper; * Interface for a class which can export the contents of the database * in a given format. */ -public interface Exporter -{ +public interface Exporter { /** * Export the database to the output stream in a given format. + * * @throws IOException */ - void exportData(Context context, DBHelper db, OutputStream output,char[] password) throws IOException, InterruptedException; + void exportData(Context context, DBHelper db, OutputStream output, char[] password) throws IOException, InterruptedException; } diff --git a/app/src/main/java/protect/card_locker/importexport/FidmeImporter.java b/app/src/main/java/protect/card_locker/importexport/FidmeImporter.java index f5453db67..23c927b8b 100644 --- a/app/src/main/java/protect/card_locker/importexport/FidmeImporter.java +++ b/app/src/main/java/protect/card_locker/importexport/FidmeImporter.java @@ -3,8 +3,6 @@ package protect.card_locker.importexport; import android.content.Context; import android.database.sqlite.SQLiteDatabase; -import com.google.zxing.BarcodeFormat; - import net.lingala.zip4j.io.inputstream.ZipInputStream; import net.lingala.zip4j.model.LocalFileHeader; @@ -23,12 +21,11 @@ import java.text.ParseException; import protect.card_locker.CatimaBarcode; import protect.card_locker.DBHelper; import protect.card_locker.FormatException; -import protect.card_locker.Utils; /** * Class for importing a database from CSV (Comma Separate Values) * formatted data. - * + *

* The database's loyalty cards are expected to appear in the CSV data. * A header is expected for the each table showing the names of the columns. */ diff --git a/app/src/main/java/protect/card_locker/importexport/ImportExportResult.java b/app/src/main/java/protect/card_locker/importexport/ImportExportResult.java index 9a8d71c08..8419d3ebe 100644 --- a/app/src/main/java/protect/card_locker/importexport/ImportExportResult.java +++ b/app/src/main/java/protect/card_locker/importexport/ImportExportResult.java @@ -1,9 +1,7 @@ package protect.card_locker.importexport; -public enum ImportExportResult -{ +public enum ImportExportResult { Success, GenericFailure, - BadPassword - ; + BadPassword; } diff --git a/app/src/main/java/protect/card_locker/importexport/Importer.java b/app/src/main/java/protect/card_locker/importexport/Importer.java index fe47d05fe..a394e455b 100644 --- a/app/src/main/java/protect/card_locker/importexport/Importer.java +++ b/app/src/main/java/protect/card_locker/importexport/Importer.java @@ -15,11 +15,11 @@ import protect.card_locker.FormatException; * Interface for a class which can import the contents of a stream * into the database. */ -public interface Importer -{ +public interface Importer { /** * Import data from the input stream in a given format into * the database. + * * @throws IOException * @throws FormatException */ diff --git a/app/src/main/java/protect/card_locker/importexport/MultiFormatExporter.java b/app/src/main/java/protect/card_locker/importexport/MultiFormatExporter.java index b45cf1eda..c4a3e2dd2 100644 --- a/app/src/main/java/protect/card_locker/importexport/MultiFormatExporter.java +++ b/app/src/main/java/protect/card_locker/importexport/MultiFormatExporter.java @@ -8,26 +8,23 @@ import java.io.OutputStream; import protect.card_locker.DBHelper; -public class MultiFormatExporter -{ +public class MultiFormatExporter { private static final String TAG = "Catima"; /** * Attempts to export data to the output stream in the * given format, if possible. - * + *

* The output stream is closed on success. * * @return ImportExportResult.Success if the database was successfully exported, * another ImportExportResult otherwise. If not Success, partial data may have been * written to the output stream, and it should be discarded. */ - public static ImportExportResult exportData(Context context, DBHelper db, OutputStream output, DataFormat format,char[] password) - { + public static ImportExportResult exportData(Context context, DBHelper db, OutputStream output, DataFormat format, char[] password) { Exporter exporter = null; - switch(format) - { + switch (format) { case Catima: exporter = new CatimaExporter(); break; @@ -36,26 +33,18 @@ public class MultiFormatExporter break; } - if(exporter != null) - { - try - { - exporter.exportData(context, db, output,password); + if (exporter != null) { + try { + exporter.exportData(context, db, output, password); return ImportExportResult.Success; - } - catch(IOException e) - { + } catch (IOException e) { Log.e(TAG, "Failed to export data", e); - } - catch(InterruptedException e) - { + } catch (InterruptedException e) { Log.e(TAG, "Failed to export data", e); } return ImportExportResult.GenericFailure; - } - else - { + } else { Log.e(TAG, "Unsupported data format exported: " + format.name()); return ImportExportResult.GenericFailure; } diff --git a/app/src/main/java/protect/card_locker/importexport/MultiFormatImporter.java b/app/src/main/java/protect/card_locker/importexport/MultiFormatImporter.java index 3463f1073..21a520f41 100644 --- a/app/src/main/java/protect/card_locker/importexport/MultiFormatImporter.java +++ b/app/src/main/java/protect/card_locker/importexport/MultiFormatImporter.java @@ -14,14 +14,13 @@ import java.text.ParseException; import protect.card_locker.DBHelper; import protect.card_locker.FormatException; -public class MultiFormatImporter -{ +public class MultiFormatImporter { private static final String TAG = "Catima"; /** * Attempts to import data from the input stream of the * given format into the database. - * + *

* The input stream is not closed, and doing so is the * responsibility of the caller. * @@ -29,12 +28,10 @@ public class MultiFormatImporter * or another result otherwise. If no Success, no data was written to * the database. */ - public static ImportExportResult importData(Context context, DBHelper db, InputStream input, DataFormat format, char[] password) - { + public static ImportExportResult importData(Context context, DBHelper db, InputStream input, DataFormat format, char[] password) { Importer importer = null; - switch(format) - { + switch (format) { case Catima: importer = new CatimaImporter(); break; @@ -49,25 +46,17 @@ public class MultiFormatImporter break; } - if (importer != null) - { - try - { + if (importer != null) { + try { importer.importData(context, db, input, password); return ImportExportResult.Success; - } - catch(ZipException e) - { + } catch (ZipException e) { return ImportExportResult.BadPassword; - } - catch(IOException | FormatException | InterruptedException | JSONException | ParseException | NullPointerException e) - { + } catch (IOException | FormatException | InterruptedException | JSONException | ParseException | NullPointerException e) { Log.e(TAG, "Failed to import data", e); } - } - else - { + } else { Log.e(TAG, "Unsupported data format imported: " + format.name()); } diff --git a/app/src/main/java/protect/card_locker/importexport/StocardImporter.java b/app/src/main/java/protect/card_locker/importexport/StocardImporter.java index 76761b83a..6d46d4045 100644 --- a/app/src/main/java/protect/card_locker/importexport/StocardImporter.java +++ b/app/src/main/java/protect/card_locker/importexport/StocardImporter.java @@ -33,22 +33,19 @@ import protect.card_locker.ZipUtils; /** * Class for importing a database from CSV (Comma Separate Values) * formatted data. - * + *

* The database's loyalty cards are expected to appear in the CSV data. * A header is expected for the each table showing the names of the columns. */ -public class StocardImporter implements Importer -{ +public class StocardImporter implements Importer { public void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException { HashMap> loyaltyCardHashMap = new HashMap<>(); HashMap> providers = new HashMap<>(); final CSVParser parser = new CSVParser(new InputStreamReader(context.getResources().openRawResource(R.raw.stocard_stores), StandardCharsets.UTF_8), CSVFormat.RFC4180.builder().setHeader().build()); - try - { - for (CSVRecord record : parser) - { + try { + for (CSVRecord record : parser) { HashMap recordData = new HashMap<>(); recordData.put("name", record.get("name")); recordData.put("barcodeFormat", record.get("barcodeFormat")); @@ -57,7 +54,7 @@ public class StocardImporter implements Importer } parser.close(); - } catch(IllegalArgumentException|IllegalStateException e) { + } catch (IllegalArgumentException | IllegalStateException e) { throw new FormatException("Issue parsing CSV data", e); } @@ -72,7 +69,7 @@ public class StocardImporter implements Importer String[] nameParts = fileName.split("/"); if (providersFileName == null) { - providersFileName = new String[] { + providersFileName = new String[]{ nameParts[0], "sync", "data", @@ -80,7 +77,7 @@ public class StocardImporter implements Importer nameParts[0], "analytics-properties.json" }; - cardBaseName = new String[] { + cardBaseName = new String[]{ nameParts[0], "sync", "data", @@ -111,9 +108,9 @@ public class StocardImporter implements Importer cardName, "_providerId", jsonObject - .getJSONObject("input_provider_reference") - .getString("identifier") - .substring("/loyalty-card-providers/".length()) + .getJSONObject("input_provider_reference") + .getString("identifier") + .substring("/loyalty-card-providers/".length()) ); if (jsonObject.has("input_barcode_format")) { @@ -131,7 +128,7 @@ public class StocardImporter implements Importer cardName, "note", ZipUtils.readJSON(zipInputStream) - .getString("content") + .getString("content") ); } else if (fileName.endsWith("/images/front.png")) { loyaltyCardHashMap = appendToLoyaltyCardHashMap( diff --git a/app/src/main/java/protect/card_locker/importexport/VoucherVaultImporter.java b/app/src/main/java/protect/card_locker/importexport/VoucherVaultImporter.java index ad38b1b62..0aa038e1b 100644 --- a/app/src/main/java/protect/card_locker/importexport/VoucherVaultImporter.java +++ b/app/src/main/java/protect/card_locker/importexport/VoucherVaultImporter.java @@ -31,12 +31,11 @@ import protect.card_locker.Utils; /** * Class for importing a database from CSV (Comma Separate Values) * formatted data. - * + *

* The database's loyalty cards are expected to appear in the CSV data. * A header is expected for the each table showing the names of the columns. */ -public class VoucherVaultImporter implements Importer -{ +public class VoucherVaultImporter implements Importer { public void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); diff --git a/app/src/main/java/protect/card_locker/preferences/Settings.java b/app/src/main/java/protect/card_locker/preferences/Settings.java index a28ac5f8a..977271ffc 100644 --- a/app/src/main/java/protect/card_locker/preferences/Settings.java +++ b/app/src/main/java/protect/card_locker/preferences/Settings.java @@ -12,44 +12,36 @@ import androidx.preference.PreferenceManager; import protect.card_locker.R; import protect.card_locker.Utils; -public class Settings -{ +public class Settings { private Context context; private SharedPreferences settings; - public Settings(Context context) - { + public Settings(Context context) { this.context = context; this.settings = PreferenceManager.getDefaultSharedPreferences(context); } - private String getResString(@StringRes int resId) - { + private String getResString(@StringRes int resId) { return context.getString(resId); } - private int getResInt(@IntegerRes int resId) - { + private int getResInt(@IntegerRes int resId) { return context.getResources().getInteger(resId); } - private String getString(@StringRes int keyId, String defaultValue) - { + private String getString(@StringRes int keyId, String defaultValue) { return settings.getString(getResString(keyId), defaultValue); } - private int getInt(@StringRes int keyId, @IntegerRes int defaultId) - { + private int getInt(@StringRes int keyId, @IntegerRes int defaultId) { return settings.getInt(getResString(keyId), getResInt(defaultId)); } - private boolean getBoolean(@StringRes int keyId, boolean defaultValue) - { + private boolean getBoolean(@StringRes int keyId, boolean defaultValue) { return settings.getBoolean(getResString(keyId), defaultValue); } - public Locale getLocale() - { + public Locale getLocale() { String value = getString(R.string.settings_key_locale, ""); if (value.length() == 0) { @@ -59,69 +51,55 @@ public class Settings return Utils.stringToLocale(value); } - public int getTheme() - { + public int getTheme() { String value = getString(R.string.settings_key_theme, getResString(R.string.settings_key_system_theme)); - if(value.equals(getResString(R.string.settings_key_light_theme))) - { + if (value.equals(getResString(R.string.settings_key_light_theme))) { return AppCompatDelegate.MODE_NIGHT_NO; - } - else if(value.equals(getResString(R.string.settings_key_dark_theme))) - { + } else if (value.equals(getResString(R.string.settings_key_dark_theme))) { return AppCompatDelegate.MODE_NIGHT_YES; } return AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM; } - public double getFontSizeScale() - { + public double getFontSizeScale() { return getInt(R.string.settings_key_max_font_size_scale, R.integer.settings_max_font_size_scale_pct) / 100.0; } - public int getSmallFont() - { + public int getSmallFont() { return 14; } - public int getMediumFont() - { + public int getMediumFont() { return 28; } - public int getLargeFont() - { + public int getLargeFont() { return 40; } - public int getFontSizeMin(int fontSize) - { + public int getFontSizeMin(int fontSize) { return (int) (Math.round(fontSize / 2.0) - 1); } - public int getFontSizeMax(int fontSize) - { + public int getFontSizeMax(int fontSize) { return (int) Math.round(fontSize * getFontSizeScale()); } - public boolean useMaxBrightnessDisplayingBarcode() - { + public boolean useMaxBrightnessDisplayingBarcode() { return getBoolean(R.string.settings_key_display_barcode_max_brightness, true); } - public boolean getLockBarcodeScreenOrientation() - { + public boolean getLockBarcodeScreenOrientation() { return getBoolean(R.string.settings_key_lock_barcode_orientation, false); } - public boolean getKeepScreenOn() - { + public boolean getKeepScreenOn() { return getBoolean(R.string.settings_key_keep_screen_on, true); } - public boolean getDisableLockscreenWhileViewingCard() - { + public boolean getDisableLockscreenWhileViewingCard() { return getBoolean(R.string.settings_key_disable_lockscreen_while_viewing_card, true); } } diff --git a/app/src/main/java/protect/card_locker/preferences/SettingsActivity.java b/app/src/main/java/protect/card_locker/preferences/SettingsActivity.java index 3e88fb87e..7bd73d668 100644 --- a/app/src/main/java/protect/card_locker/preferences/SettingsActivity.java +++ b/app/src/main/java/protect/card_locker/preferences/SettingsActivity.java @@ -24,19 +24,16 @@ import protect.card_locker.CatimaAppCompatActivity; import protect.card_locker.R; import protect.card_locker.Utils; -public class SettingsActivity extends CatimaAppCompatActivity -{ +public class SettingsActivity extends CatimaAppCompatActivity { @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.settings); setContentView(R.layout.settings_activity); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); - if(actionBar != null) - { + if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } @@ -48,12 +45,10 @@ public class SettingsActivity extends CatimaAppCompatActivity } @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); - if(id == android.R.id.home) - { + if (id == android.R.id.home) { finish(); return true; } @@ -61,8 +56,7 @@ public class SettingsActivity extends CatimaAppCompatActivity return super.onOptionsItemSelected(item); } - public static class SettingsFragment extends PreferenceFragmentCompat - { + public static class SettingsFragment extends PreferenceFragmentCompat { private static final String DIALOG_FRAGMENT_TAG = "SettingsFragment"; @Override