680: Cleanup DBHelper r=TheLastProject a=TheLastProject

Should fix #661 

Supersedes #678 

While #678 does fix the issue too, the real issue was that an importer could cause such a state issue. So I've instead been seriously cleaning up. While all the tests pass, I do want to test this slightly longer before merging it into master.

Co-authored-by: Sylvia van Os <sylvia@hackerchick.me>
This commit is contained in:
bors[bot]
2021-12-14 19:24:29 +00:00
committed by GitHub
28 changed files with 614 additions and 708 deletions

View File

@@ -1,6 +1,7 @@
package protect.card_locker;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
@@ -17,7 +18,7 @@ import androidx.recyclerview.widget.RecyclerView;
*/
public class CardShortcutConfigure extends AppCompatActivity implements LoyaltyCardCursorAdapter.CardAdapterListener {
static final String TAG = "Catima";
final DBHelper mDb = new DBHelper(this);
final SQLiteDatabase mDatabase = new DBHelper(this).getReadableDatabase();
@Override
public void onCreate(Bundle bundle) {
@@ -31,10 +32,8 @@ public class CardShortcutConfigure extends AppCompatActivity implements LoyaltyC
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(R.string.shortcutSelectCard);
final DBHelper db = new DBHelper(this);
// If there are no cards, bail
if (db.getLoyaltyCardCount() == 0) {
if (DBHelper.getLoyaltyCardCount(mDatabase) == 0) {
Toast.makeText(this, R.string.noCardsMessage, Toast.LENGTH_LONG).show();
finish();
}
@@ -45,13 +44,13 @@ public class CardShortcutConfigure extends AppCompatActivity implements LoyaltyC
layoutManager.setSpanCount(getResources().getInteger(R.integer.main_view_card_columns));
}
Cursor cardCursor = db.getLoyaltyCardCursor();
Cursor cardCursor = DBHelper.getLoyaltyCardCursor(mDatabase);
final LoyaltyCardCursorAdapter adapter = new LoyaltyCardCursorAdapter(this, cardCursor, this);
cardList.setAdapter(adapter);
}
private void onClickAction(int position) {
Cursor selected = mDb.getLoyaltyCardCursor();
Cursor selected = DBHelper.getLoyaltyCardCursor(mDatabase);
selected.moveToPosition(position);
LoyaltyCard loyaltyCard = LoyaltyCard.toLoyaltyCard(selected);

View File

@@ -5,6 +5,7 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import android.os.Build;
@@ -27,12 +28,12 @@ public class CardsOnPowerScreenService extends ControlsProviderService {
public static final String PREFIX = "catima-";
static final String TAG = "Catima";
private final DBHelper dbHelper = new DBHelper(this);
private final SQLiteDatabase mDatabase = new DBHelper(this).getReadableDatabase();
@NonNull
@Override
public Flow.Publisher<Control> createPublisherForAllAvailable() {
Cursor loyaltyCardCursor = dbHelper.getLoyaltyCardCursor();
Cursor loyaltyCardCursor = DBHelper.getLoyaltyCardCursor(mDatabase);
return subscriber -> {
while (loyaltyCardCursor.moveToNext()) {
LoyaltyCard card = LoyaltyCard.toLoyaltyCard(loyaltyCardCursor);
@@ -64,7 +65,7 @@ public class CardsOnPowerScreenService extends ControlsProviderService {
try {
Integer cardId = this.controlIdToCardId(controlId);
LoyaltyCard card = dbHelper.getLoyaltyCard(cardId);
LoyaltyCard card = DBHelper.getLoyaltyCard(mDatabase, cardId);
Intent openIntent = new Intent(this, LoyaltyCardViewActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("id", card.id);

View File

@@ -111,7 +111,6 @@ public class DBHelper extends SQLiteOpenHelper {
"tokenize=unicode61);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2 && newVersion >= 2) {
@@ -305,7 +304,7 @@ public class DBHelper extends SQLiteOpenHelper {
}
}
private ContentValues generateFTSContentValues(final int id, final String store, final String note) {
private static ContentValues generateFTSContentValues(final int id, final String store, final String note) {
// FTS on Android is severely limited and can only search for word starting with a certain string
// So for each word, we grab every single substring
// This makes it possible to find Décathlon by searching both de and cat, for example
@@ -337,22 +336,21 @@ public class DBHelper extends SQLiteOpenHelper {
return ftsContentValues;
}
private void insertFTS(final SQLiteDatabase db, final int id, final String store, final String note) {
private static void insertFTS(final SQLiteDatabase db, final int id, final String store, final String note) {
db.insert(LoyaltyCardDbFTS.TABLE, null, generateFTSContentValues(id, store, note));
}
private void updateFTS(final SQLiteDatabase db, final int id, final String store, final String note) {
private static void updateFTS(final SQLiteDatabase db, final int id, final String store, final String note) {
db.update(LoyaltyCardDbFTS.TABLE, generateFTSContentValues(id, store, note),
whereAttrs(LoyaltyCardDbFTS.ID), withArgs(id));
}
public long insertLoyaltyCard(final String store, final String note, final Date expiry,
final BigDecimal balance, final Currency balanceType,
final String cardId, final String barcodeId,
final CatimaBarcode barcodeType, final Integer headerColor,
final int starStatus, final Long lastUsed) {
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
public static long insertLoyaltyCard(
final SQLiteDatabase database, final String store, final String note, final Date expiry,
final BigDecimal balance, final Currency balanceType, final String cardId,
final String barcodeId, final CatimaBarcode barcodeType, final Integer headerColor,
final int starStatus, final Long lastUsed) {
database.beginTransaction();
// Card
ContentValues contentValues = new ContentValues();
@@ -367,56 +365,23 @@ public class DBHelper extends SQLiteOpenHelper {
contentValues.put(LoyaltyCardDbIds.HEADER_COLOR, headerColor);
contentValues.put(LoyaltyCardDbIds.STAR_STATUS, starStatus);
contentValues.put(LoyaltyCardDbIds.LAST_USED, lastUsed != null ? lastUsed : Utils.getUnixTime());
long id = db.insert(LoyaltyCardDbIds.TABLE, null, contentValues);
long id = database.insert(LoyaltyCardDbIds.TABLE, null, contentValues);
// FTS
insertFTS(db, (int) id, store, note);
insertFTS(database, (int) id, store, note);
db.setTransactionSuccessful();
db.endTransaction();
database.setTransactionSuccessful();
database.endTransaction();
return id;
}
public long insertLoyaltyCard(final SQLiteDatabase db, final String store,
final String note, final Date expiry, final BigDecimal balance,
final Currency balanceType, final String cardId,
final String barcodeId, final CatimaBarcode barcodeType,
final Integer headerColor, final int starStatus,
final Long lastUsed) {
db.beginTransaction();
// Card
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbIds.STORE, store);
contentValues.put(LoyaltyCardDbIds.NOTE, note);
contentValues.put(LoyaltyCardDbIds.EXPIRY, expiry != null ? expiry.getTime() : null);
contentValues.put(LoyaltyCardDbIds.BALANCE, balance.toString());
contentValues.put(LoyaltyCardDbIds.BALANCE_TYPE, balanceType != null ? balanceType.getCurrencyCode() : null);
contentValues.put(LoyaltyCardDbIds.CARD_ID, cardId);
contentValues.put(LoyaltyCardDbIds.BARCODE_ID, barcodeId);
contentValues.put(LoyaltyCardDbIds.BARCODE_TYPE, barcodeType != null ? barcodeType.name() : null);
contentValues.put(LoyaltyCardDbIds.HEADER_COLOR, headerColor);
contentValues.put(LoyaltyCardDbIds.STAR_STATUS, starStatus);
contentValues.put(LoyaltyCardDbIds.LAST_USED, lastUsed != null ? lastUsed : Utils.getUnixTime());
long id = db.insert(LoyaltyCardDbIds.TABLE, null, contentValues);
// FTS
insertFTS(db, (int) id, store, note);
db.setTransactionSuccessful();
db.endTransaction();
return id;
}
public long insertLoyaltyCard(final SQLiteDatabase db, final int id, final String store,
final String note, final Date expiry, final BigDecimal balance,
final Currency balanceType, final String cardId,
final String barcodeId, final CatimaBarcode barcodeType,
final Integer headerColor, final int starStatus,
final Long lastUsed) {
db.beginTransaction();
public static long insertLoyaltyCard(
final SQLiteDatabase database, final int id, final String store, final String note,
final Date expiry, final BigDecimal balance, final Currency balanceType,
final String cardId, final String barcodeId, final CatimaBarcode barcodeType,
final Integer headerColor, final int starStatus, final Long lastUsed) {
database.beginTransaction();
// Card
ContentValues contentValues = new ContentValues();
@@ -432,24 +397,23 @@ public class DBHelper extends SQLiteOpenHelper {
contentValues.put(LoyaltyCardDbIds.HEADER_COLOR, headerColor);
contentValues.put(LoyaltyCardDbIds.STAR_STATUS, starStatus);
contentValues.put(LoyaltyCardDbIds.LAST_USED, lastUsed != null ? lastUsed : Utils.getUnixTime());
db.insert(LoyaltyCardDbIds.TABLE, null, contentValues);
database.insert(LoyaltyCardDbIds.TABLE, null, contentValues);
// FTS
insertFTS(db, id, store, note);
insertFTS(database, id, store, note);
db.setTransactionSuccessful();
db.endTransaction();
database.setTransactionSuccessful();
database.endTransaction();
return id;
}
public boolean updateLoyaltyCard(final int id, final String store, final String note,
final Date expiry, final BigDecimal balance,
final Currency balanceType, final String cardId,
final String barcodeId, final CatimaBarcode barcodeType,
final Integer headerColor) {
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
public static boolean updateLoyaltyCard(
SQLiteDatabase database, final int id, final String store, final String note,
final Date expiry, final BigDecimal balance, final Currency balanceType,
final String cardId, final String barcodeId, final CatimaBarcode barcodeType,
final Integer headerColor) {
database.beginTransaction();
// Card
ContentValues contentValues = new ContentValues();
@@ -462,53 +426,49 @@ public class DBHelper extends SQLiteOpenHelper {
contentValues.put(LoyaltyCardDbIds.BARCODE_ID, barcodeId);
contentValues.put(LoyaltyCardDbIds.BARCODE_TYPE, barcodeType != null ? barcodeType.name() : null);
contentValues.put(LoyaltyCardDbIds.HEADER_COLOR, headerColor);
int rowsUpdated = db.update(LoyaltyCardDbIds.TABLE, contentValues,
int rowsUpdated = database.update(LoyaltyCardDbIds.TABLE, contentValues,
whereAttrs(LoyaltyCardDbIds.ID), withArgs(id));
// FTS
updateFTS(db, id, store, note);
updateFTS(database, id, store, note);
db.setTransactionSuccessful();
db.endTransaction();
database.setTransactionSuccessful();
database.endTransaction();
return (rowsUpdated == 1);
}
public boolean updateLoyaltyCardStarStatus(final int id, final int starStatus) {
SQLiteDatabase db = getWritableDatabase();
public static boolean updateLoyaltyCardStarStatus(SQLiteDatabase database, final int id, final int starStatus) {
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbIds.STAR_STATUS, starStatus);
int rowsUpdated = db.update(LoyaltyCardDbIds.TABLE, contentValues,
int rowsUpdated = database.update(LoyaltyCardDbIds.TABLE, contentValues,
whereAttrs(LoyaltyCardDbIds.ID),
withArgs(id));
return (rowsUpdated == 1);
}
public boolean updateLoyaltyCardLastUsed(final int id) {
SQLiteDatabase db = getWritableDatabase();
public static boolean updateLoyaltyCardLastUsed(SQLiteDatabase database, final int id) {
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbIds.LAST_USED, System.currentTimeMillis() / 1000);
int rowsUpdated = db.update(LoyaltyCardDbIds.TABLE, contentValues,
int rowsUpdated = database.update(LoyaltyCardDbIds.TABLE, contentValues,
whereAttrs(LoyaltyCardDbIds.ID),
withArgs(id));
return (rowsUpdated == 1);
}
public boolean updateLoyaltyCardZoomLevel(int loyaltyCardId, int zoomLevel) {
SQLiteDatabase db = getWritableDatabase();
public static boolean updateLoyaltyCardZoomLevel(SQLiteDatabase database, int loyaltyCardId, int zoomLevel) {
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,
int rowsUpdated = database.update(LoyaltyCardDbIds.TABLE, contentValues,
whereAttrs(LoyaltyCardDbIds.ID),
withArgs(loyaltyCardId));
Log.d("updateLoyaltyCardZLevel", "Rows changed = " + rowsUpdated);
return (rowsUpdated == 1);
}
public LoyaltyCard getLoyaltyCard(final int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor data = db.query(LoyaltyCardDbIds.TABLE, null, whereAttrs(LoyaltyCardDbIds.ID), withArgs(id), null, null, null);
public static LoyaltyCard getLoyaltyCard(SQLiteDatabase database, final int id) {
Cursor data = database.query(LoyaltyCardDbIds.TABLE, null, whereAttrs(LoyaltyCardDbIds.ID), withArgs(id), null, null, null);
LoyaltyCard card = null;
@@ -522,9 +482,8 @@ public class DBHelper extends SQLiteOpenHelper {
return card;
}
public List<Group> getLoyaltyCardGroups(final int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor data = db.rawQuery("select * from " + LoyaltyCardDbGroups.TABLE + " g " +
public static List<Group> getLoyaltyCardGroups(SQLiteDatabase database, final int id) {
Cursor data = database.rawQuery("select * from " + LoyaltyCardDbGroups.TABLE + " g " +
" LEFT JOIN " + LoyaltyCardDbIdsGroups.TABLE + " ig ON ig." + LoyaltyCardDbIdsGroups.groupID + " = g." + LoyaltyCardDbGroups.ID +
" where " + LoyaltyCardDbIdsGroups.cardID + "=?" +
" ORDER BY " + LoyaltyCardDbIdsGroups.groupID, withArgs(id));
@@ -547,11 +506,9 @@ public class DBHelper extends SQLiteOpenHelper {
return groups;
}
public void setLoyaltyCardGroups(final int id, List<Group> groups) {
SQLiteDatabase db = getWritableDatabase();
public static void setLoyaltyCardGroups(SQLiteDatabase database, final int id, List<Group> groups) {
// First delete lookup table entries associated with this card
db.delete(LoyaltyCardDbIdsGroups.TABLE,
database.delete(LoyaltyCardDbIdsGroups.TABLE,
whereAttrs(LoyaltyCardDbIdsGroups.cardID),
withArgs(id));
@@ -560,39 +517,23 @@ public class DBHelper extends SQLiteOpenHelper {
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbIdsGroups.cardID, id);
contentValues.put(LoyaltyCardDbIdsGroups.groupID, group._id);
db.insert(LoyaltyCardDbIdsGroups.TABLE, null, contentValues);
database.insert(LoyaltyCardDbIdsGroups.TABLE, null, contentValues);
}
}
public void setLoyaltyCardGroups(final SQLiteDatabase db, final int id, List<Group> groups) {
// First delete lookup table entries associated with this card
db.delete(LoyaltyCardDbIdsGroups.TABLE,
whereAttrs(LoyaltyCardDbIdsGroups.cardID),
withArgs(id));
// Then create entries for selected values
for (Group group : groups) {
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbIdsGroups.cardID, id);
contentValues.put(LoyaltyCardDbIdsGroups.groupID, group._id);
db.insert(LoyaltyCardDbIdsGroups.TABLE, null, contentValues);
}
}
public boolean deleteLoyaltyCard(Context context, final int id) {
SQLiteDatabase db = getWritableDatabase();
public static boolean deleteLoyaltyCard(SQLiteDatabase database, Context context, final int id) {
// Delete card
int rowsDeleted = db.delete(LoyaltyCardDbIds.TABLE,
int rowsDeleted = database.delete(LoyaltyCardDbIds.TABLE,
whereAttrs(LoyaltyCardDbIds.ID),
withArgs(id));
// And delete lookup table entries associated with this card
db.delete(LoyaltyCardDbIdsGroups.TABLE,
database.delete(LoyaltyCardDbIdsGroups.TABLE,
whereAttrs(LoyaltyCardDbIdsGroups.cardID),
withArgs(id));
// Delete FTS table entries
db.delete(LoyaltyCardDbFTS.TABLE,
database.delete(LoyaltyCardDbFTS.TABLE,
whereAttrs(LoyaltyCardDbFTS.ID),
withArgs(id));
@@ -608,9 +549,9 @@ public class DBHelper extends SQLiteOpenHelper {
return (rowsDeleted == 1);
}
public Cursor getLoyaltyCardCursor() {
public static Cursor getLoyaltyCardCursor(SQLiteDatabase database) {
// An empty string will match everything
return getLoyaltyCardCursor("");
return getLoyaltyCardCursor(database, "");
}
/**
@@ -619,8 +560,8 @@ public class DBHelper extends SQLiteOpenHelper {
* @param filter
* @return Cursor
*/
public Cursor getLoyaltyCardCursor(final String filter) {
return getLoyaltyCardCursor(filter, null);
public static Cursor getLoyaltyCardCursor(SQLiteDatabase database, final String filter) {
return getLoyaltyCardCursor(database, filter, null);
}
/**
@@ -630,8 +571,8 @@ public class DBHelper extends SQLiteOpenHelper {
* @param group
* @return Cursor
*/
public Cursor getLoyaltyCardCursor(final String filter, Group group) {
return getLoyaltyCardCursor(filter, group, LoyaltyCardOrder.Alpha, LoyaltyCardOrderDirection.Ascending);
public static Cursor getLoyaltyCardCursor(SQLiteDatabase database, final String filter, Group group) {
return getLoyaltyCardCursor(database, filter, group, LoyaltyCardOrder.Alpha, LoyaltyCardOrderDirection.Ascending);
}
/**
@@ -642,14 +583,12 @@ public class DBHelper extends SQLiteOpenHelper {
* @param order
* @return Cursor
*/
public Cursor getLoyaltyCardCursor(String filter, Group group, LoyaltyCardOrder order, LoyaltyCardOrderDirection direction) {
public static Cursor getLoyaltyCardCursor(SQLiteDatabase database, String filter, Group group, LoyaltyCardOrder order, LoyaltyCardOrderDirection direction) {
StringBuilder groupFilter = new StringBuilder();
String limitString = "";
SQLiteDatabase db = getReadableDatabase();
if (group != null) {
List<Integer> allowedIds = getGroupCardIds(group._id);
List<Integer> allowedIds = getGroupCardIds(database, group._id);
// Empty group
if (!allowedIds.isEmpty()) {
@@ -669,7 +608,7 @@ public class DBHelper extends SQLiteOpenHelper {
String orderField = getFieldForOrder(order);
return db.rawQuery("SELECT " + LoyaltyCardDbIds.TABLE + ".* FROM " + LoyaltyCardDbIds.TABLE +
return database.rawQuery("SELECT " + LoyaltyCardDbIds.TABLE + ".* FROM " + LoyaltyCardDbIds.TABLE +
" JOIN " + LoyaltyCardDbFTS.TABLE +
" ON " + LoyaltyCardDbFTS.TABLE + "." + LoyaltyCardDbFTS.ID + " = " + LoyaltyCardDbIds.TABLE + "." + LoyaltyCardDbIds.ID +
(filter.trim().isEmpty() ? " " : " AND " + LoyaltyCardDbFTS.TABLE + " MATCH ? ") +
@@ -686,9 +625,8 @@ public class DBHelper extends SQLiteOpenHelper {
*
* @return Integer
*/
public int getLoyaltyCardCount() {
SQLiteDatabase db = getReadableDatabase();
return (int) DatabaseUtils.queryNumEntries(db, LoyaltyCardDbIds.TABLE);
public static int getLoyaltyCardCount(SQLiteDatabase database) {
return (int) DatabaseUtils.queryNumEntries(database, LoyaltyCardDbIds.TABLE);
}
/**
@@ -696,15 +634,13 @@ public class DBHelper extends SQLiteOpenHelper {
*
* @return Cursor
*/
public Cursor getGroupCursor() {
SQLiteDatabase db = getReadableDatabase();
return db.rawQuery("select * from " + LoyaltyCardDbGroups.TABLE +
public static Cursor getGroupCursor(SQLiteDatabase database) {
return database.rawQuery("select * from " + LoyaltyCardDbGroups.TABLE +
" ORDER BY " + LoyaltyCardDbGroups.ORDER + " ASC," + LoyaltyCardDbGroups.ID + " COLLATE NOCASE ASC", null, null);
}
public List<Group> getGroups() {
Cursor data = getGroupCursor();
public static List<Group> getGroups(SQLiteDatabase database) {
Cursor data = getGroupCursor(database);
List<Group> groups = new ArrayList<>();
@@ -722,15 +658,14 @@ public class DBHelper extends SQLiteOpenHelper {
return groups;
}
public void reorderGroups(final List<Group> groups) {
public static void reorderGroups(SQLiteDatabase database, final List<Group> groups) {
Integer order = 0;
SQLiteDatabase db = getWritableDatabase();
for (Group group : groups) {
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbGroups.ORDER, order);
db.update(LoyaltyCardDbGroups.TABLE, contentValues,
database.update(LoyaltyCardDbGroups.TABLE, contentValues,
whereAttrs(LoyaltyCardDbGroups.ID),
withArgs(group._id));
@@ -738,9 +673,8 @@ public class DBHelper extends SQLiteOpenHelper {
}
}
public Group getGroup(final String groupName) {
SQLiteDatabase db = getReadableDatabase();
Cursor data = db.query(LoyaltyCardDbGroups.TABLE, null,
public static Group getGroup(SQLiteDatabase database, final String groupName) {
Cursor data = database.query(LoyaltyCardDbGroups.TABLE, null,
whereAttrs(LoyaltyCardDbGroups.ID), withArgs(groupName), null, null, null);
Group group = null;
@@ -753,14 +687,12 @@ public class DBHelper extends SQLiteOpenHelper {
return group;
}
public int getGroupCount() {
SQLiteDatabase db = getReadableDatabase();
return (int) DatabaseUtils.queryNumEntries(db, LoyaltyCardDbGroups.TABLE);
public static int getGroupCount(SQLiteDatabase database) {
return (int) DatabaseUtils.queryNumEntries(database, LoyaltyCardDbGroups.TABLE);
}
public List<Integer> getGroupCardIds(final String groupName) {
SQLiteDatabase db = getReadableDatabase();
Cursor data = db.query(LoyaltyCardDbIdsGroups.TABLE, withArgs(LoyaltyCardDbIdsGroups.cardID),
public static List<Integer> getGroupCardIds(SQLiteDatabase database, final String groupName) {
Cursor data = database.query(LoyaltyCardDbIdsGroups.TABLE, withArgs(LoyaltyCardDbIdsGroups.cardID),
whereAttrs(LoyaltyCardDbIdsGroups.groupID), withArgs(groupName), null, null, null);
List<Integer> cardIds = new ArrayList<>();
@@ -779,99 +711,85 @@ public class DBHelper extends SQLiteOpenHelper {
return cardIds;
}
public long insertGroup(final String name) {
public static long insertGroup(SQLiteDatabase database, final String name) {
if (name.isEmpty()) return -1;
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbGroups.ID, name);
contentValues.put(LoyaltyCardDbGroups.ORDER, getGroupCount());
return db.insert(LoyaltyCardDbGroups.TABLE, null, contentValues);
contentValues.put(LoyaltyCardDbGroups.ORDER, getGroupCount(database));
return database.insert(LoyaltyCardDbGroups.TABLE, null, contentValues);
}
public boolean insertGroup(final SQLiteDatabase db, final String name) {
ContentValues contentValues = new ContentValues();
contentValues.put(LoyaltyCardDbGroups.ID, name);
contentValues.put(LoyaltyCardDbGroups.ORDER, getGroupCount());
final long newId = db.insert(LoyaltyCardDbGroups.TABLE, null, contentValues);
return newId != -1;
}
public boolean updateGroup(final String groupName, final String newName) {
public static boolean updateGroup(SQLiteDatabase database, final String groupName, final String newName) {
if (newName.isEmpty()) return false;
boolean success = false;
SQLiteDatabase db = getWritableDatabase();
ContentValues groupContentValues = new ContentValues();
groupContentValues.put(LoyaltyCardDbGroups.ID, newName);
ContentValues lookupContentValues = new ContentValues();
lookupContentValues.put(LoyaltyCardDbIdsGroups.groupID, newName);
db.beginTransaction();
database.beginTransaction();
try {
// Update group name
int groupsChanged = db.update(LoyaltyCardDbGroups.TABLE, groupContentValues,
int groupsChanged = database.update(LoyaltyCardDbGroups.TABLE, groupContentValues,
whereAttrs(LoyaltyCardDbGroups.ID),
withArgs(groupName));
// Also update lookup tables
db.update(LoyaltyCardDbIdsGroups.TABLE, lookupContentValues,
database.update(LoyaltyCardDbIdsGroups.TABLE, lookupContentValues,
whereAttrs(LoyaltyCardDbIdsGroups.groupID),
withArgs(groupName));
if (groupsChanged == 1) {
db.setTransactionSuccessful();
database.setTransactionSuccessful();
success = true;
}
} catch (SQLiteException e) {
} catch (SQLiteException ignored) {
} finally {
db.endTransaction();
database.endTransaction();
}
return success;
}
public boolean deleteGroup(final String groupName) {
public static boolean deleteGroup(SQLiteDatabase database, final String groupName) {
boolean success = false;
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
database.beginTransaction();
try {
// Delete group
int groupsDeleted = db.delete(LoyaltyCardDbGroups.TABLE,
int groupsDeleted = database.delete(LoyaltyCardDbGroups.TABLE,
whereAttrs(LoyaltyCardDbGroups.ID),
withArgs(groupName));
// And delete lookup table entries associated with this group
db.delete(LoyaltyCardDbIdsGroups.TABLE,
database.delete(LoyaltyCardDbIdsGroups.TABLE,
whereAttrs(LoyaltyCardDbIdsGroups.groupID),
withArgs(groupName));
if (groupsDeleted == 1) {
db.setTransactionSuccessful();
database.setTransactionSuccessful();
success = true;
}
} finally {
db.endTransaction();
database.endTransaction();
}
// Reorder after delete to ensure no bad order IDs
reorderGroups(getGroups());
reorderGroups(database, getGroups(database));
return success;
}
public int getGroupCardCount(final String groupName) {
SQLiteDatabase db = getReadableDatabase();
return (int) DatabaseUtils.queryNumEntries(db, LoyaltyCardDbIdsGroups.TABLE,
public static int getGroupCardCount(SQLiteDatabase database, final String groupName) {
return (int) DatabaseUtils.queryNumEntries(database, LoyaltyCardDbIdsGroups.TABLE,
whereAttrs(LoyaltyCardDbIdsGroups.groupID), withArgs(groupName));
}
private String whereAttrs(String... attrs) {
static private String whereAttrs(String... attrs) {
if (attrs.length == 0) {
return null;
}
@@ -882,13 +800,13 @@ public class DBHelper extends SQLiteOpenHelper {
return whereClause.toString();
}
private String[] withArgs(Object... object) {
static private String[] withArgs(Object... object) {
return Arrays.stream(object)
.map(String::valueOf)
.toArray(String[]::new);
}
private String getFieldForOrder(LoyaltyCardOrder order) {
private static String getFieldForOrder(LoyaltyCardOrder order) {
if (order == LoyaltyCardOrder.Alpha) {
return LoyaltyCardDbIds.STORE;
}
@@ -904,7 +822,7 @@ public class DBHelper extends SQLiteOpenHelper {
throw new IllegalArgumentException("Unknown order " + order);
}
private String getDbDirection(LoyaltyCardOrder order, LoyaltyCardOrderDirection direction) {
private static String getDbDirection(LoyaltyCardOrder order, LoyaltyCardOrderDirection direction) {
if (order == LoyaltyCardOrder.LastUsed) {
// We want the default sorting to put the most recently used first
return direction == LoyaltyCardOrderDirection.Descending ? "ASC" : "DESC";

View File

@@ -2,6 +2,7 @@ package protect.card_locker;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -16,7 +17,7 @@ public class GroupCursorAdapter extends BaseCursorAdapter<GroupCursorAdapter.Gro
Settings mSettings;
private final Context mContext;
private final GroupAdapterListener mListener;
DBHelper mDb;
SQLiteDatabase mDatabase;
public GroupCursorAdapter(Context inputContext, Cursor inputCursor, GroupAdapterListener inputListener) {
super(inputCursor, DBHelper.LoyaltyCardDbGroups.ORDER);
@@ -24,7 +25,7 @@ public class GroupCursorAdapter extends BaseCursorAdapter<GroupCursorAdapter.Gro
mSettings = new Settings(inputContext);
mContext = inputContext.getApplicationContext();
mListener = inputListener;
mDb = new DBHelper(inputContext);
mDatabase = new DBHelper(inputContext).getReadableDatabase();
swapCursor(inputCursor);
}
@@ -41,7 +42,7 @@ public class GroupCursorAdapter extends BaseCursorAdapter<GroupCursorAdapter.Gro
inputHolder.mName.setText(group._id);
int groupCardCount = mDb.getGroupCardCount(group._id);
int groupCardCount = DBHelper.getGroupCardCount(mDatabase, group._id);
inputHolder.mCardCount.setText(mContext.getResources().getQuantityString(R.plurals.groupCardCount, groupCardCount, groupCardCount));
inputHolder.mName.setTextSize(mSettings.getFontSizeMax(mSettings.getMediumFont()));

View File

@@ -4,6 +4,7 @@ import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.io.IOException;
@@ -59,20 +60,20 @@ public class ImportExportTask implements CompatCallable<ImportExportResult> {
this.listener = listener;
}
private ImportExportResult performImport(Context context, InputStream stream, DBHelper db, char[] password) {
ImportExportResult importResult = MultiFormatImporter.importData(context, db, stream, format, password);
private ImportExportResult performImport(Context context, InputStream stream, SQLiteDatabase database, char[] password) {
ImportExportResult importResult = MultiFormatImporter.importData(context, database, stream, format, password);
Log.i(TAG, "Import result: " + importResult.name());
return importResult;
}
private ImportExportResult performExport(Context context, OutputStream stream, DBHelper db, char[] password) {
private ImportExportResult performExport(Context context, OutputStream stream, SQLiteDatabase database, char[] password) {
ImportExportResult result = ImportExportResult.GenericFailure;
try {
OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
result = MultiFormatExporter.exportData(context, db, stream, format, password);
result = MultiFormatExporter.exportData(context, database, stream, format, password);
writer.close();
} catch (IOException e) {
Log.e(TAG, "Unable to export file", e);
@@ -98,15 +99,17 @@ public class ImportExportTask implements CompatCallable<ImportExportResult> {
}
protected ImportExportResult doInBackground(Void... nothing) {
final DBHelper db = new DBHelper(activity);
final SQLiteDatabase database = new DBHelper(activity).getWritableDatabase();
ImportExportResult result;
if (doImport) {
result = performImport(activity.getApplicationContext(), inputStream, db, password);
result = performImport(activity.getApplicationContext(), inputStream, database, password);
} else {
result = performExport(activity.getApplicationContext(), outputStream, db, password);
result = performExport(activity.getApplicationContext(), outputStream, database, password);
}
database.close();
return result;
}

View File

@@ -9,6 +9,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
@@ -142,7 +143,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
Uri importLoyaltyCardUri = null;
DBHelper db;
SQLiteDatabase mDatabase;
ImportURIHelper importUriHelper;
boolean hasChanged = false;
@@ -292,9 +293,10 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
actionBar.setDisplayHomeAsUpEnabled(true);
}
mDatabase = new DBHelper(this).getWritableDatabase();
extractIntentFields(getIntent());
db = new DBHelper(this);
importUriHelper = new ImportURIHelper(this);
for (Currency currency : Currency.getAvailableCurrencies()) {
@@ -740,7 +742,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
if (tempLoyaltyCard == null) {
if (updateLoyaltyCard) {
tempLoyaltyCard = db.getLoyaltyCard(loyaltyCardId);
tempLoyaltyCard = DBHelper.getLoyaltyCard(mDatabase, loyaltyCardId);
if (tempLoyaltyCard == null) {
Log.w(TAG, "Could not lookup loyalty card " + loyaltyCardId);
Toast.makeText(this, R.string.noCardExistsError, Toast.LENGTH_LONG).show();
@@ -803,9 +805,9 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
barcodeTypeField.setText(tempLoyaltyCard.barcodeType != null ? tempLoyaltyCard.barcodeType.prettyName() : getString(R.string.noBarcode));
if (groupsChips.getChildCount() == 0) {
List<Group> existingGroups = db.getGroups();
List<Group> existingGroups = DBHelper.getGroups(mDatabase);
List<Group> loyaltyCardGroups = db.getLoyaltyCardGroups(loyaltyCardId);
List<Group> loyaltyCardGroups = DBHelper.getLoyaltyCardGroups(mDatabase, loyaltyCardId);
if (existingGroups.isEmpty()) {
groupsChips.setVisibility(View.GONE);
@@ -813,7 +815,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
groupsChips.setVisibility(View.VISIBLE);
}
for (Group group : db.getGroups()) {
for (Group group : DBHelper.getGroups(mDatabase)) {
Chip chip = (Chip) getLayoutInflater().inflate(R.layout.layout_chip_choice, groupsChips, false);
chip.setText(group._id);
chip.setTag(group);
@@ -1269,7 +1271,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
}
if (updateLoyaltyCard) { //update of "starStatus" not necessary, since it cannot be changed in this activity (only in ViewActivity)
db.updateLoyaltyCard(loyaltyCardId, tempLoyaltyCard.store, tempLoyaltyCard.note, tempLoyaltyCard.expiry, tempLoyaltyCard.balance, tempLoyaltyCard.balanceType, tempLoyaltyCard.cardId, tempLoyaltyCard.barcodeId, tempLoyaltyCard.barcodeType, tempLoyaltyCard.headerColor);
DBHelper.updateLoyaltyCard(mDatabase, loyaltyCardId, tempLoyaltyCard.store, tempLoyaltyCard.note, tempLoyaltyCard.expiry, tempLoyaltyCard.balance, tempLoyaltyCard.balanceType, tempLoyaltyCard.cardId, tempLoyaltyCard.barcodeId, tempLoyaltyCard.barcodeType, tempLoyaltyCard.headerColor);
try {
Utils.saveCardImage(this, (Bitmap) cardImageFront.getTag(), loyaltyCardId, ImageLocationType.front);
Utils.saveCardImage(this, (Bitmap) cardImageBack.getTag(), loyaltyCardId, ImageLocationType.back);
@@ -1279,7 +1281,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
}
Log.i(TAG, "Updated " + loyaltyCardId + " to " + cardId);
} else {
loyaltyCardId = (int) db.insertLoyaltyCard(tempLoyaltyCard.store, tempLoyaltyCard.note, tempLoyaltyCard.expiry, tempLoyaltyCard.balance, tempLoyaltyCard.balanceType, tempLoyaltyCard.cardId, tempLoyaltyCard.barcodeId, tempLoyaltyCard.barcodeType, tempLoyaltyCard.headerColor, 0, tempLoyaltyCard.lastUsed);
loyaltyCardId = (int) DBHelper.insertLoyaltyCard(mDatabase, tempLoyaltyCard.store, tempLoyaltyCard.note, tempLoyaltyCard.expiry, tempLoyaltyCard.balance, tempLoyaltyCard.balanceType, tempLoyaltyCard.cardId, tempLoyaltyCard.barcodeId, tempLoyaltyCard.barcodeType, tempLoyaltyCard.headerColor, 0, tempLoyaltyCard.lastUsed);
try {
Utils.saveCardImage(this, (Bitmap) cardImageFront.getTag(), loyaltyCardId, ImageLocationType.front);
Utils.saveCardImage(this, (Bitmap) cardImageBack.getTag(), loyaltyCardId, ImageLocationType.back);
@@ -1289,9 +1291,9 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
}
}
db.setLoyaltyCardGroups(loyaltyCardId, selectedGroups);
DBHelper.setLoyaltyCardGroups(mDatabase, loyaltyCardId, selectedGroups);
ShortcutHelper.updateShortcuts(this, db.getLoyaltyCard(loyaltyCardId));
ShortcutHelper.updateShortcuts(this, DBHelper.getLoyaltyCard(mDatabase, loyaltyCardId));
finish();
}
@@ -1323,8 +1325,7 @@ public class LoyaltyCardEditActivity extends CatimaAppCompatActivity {
builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
Log.e(TAG, "Deleting card: " + loyaltyCardId);
DBHelper db = new DBHelper(LoyaltyCardEditActivity.this);
db.deleteLoyaltyCard(LoyaltyCardEditActivity.this, loyaltyCardId);
DBHelper.deleteLoyaltyCard(mDatabase, LoyaltyCardEditActivity.this, loyaltyCardId);
ShortcutHelper.removeShortcut(LoyaltyCardEditActivity.this, loyaltyCardId);

View File

@@ -3,6 +3,7 @@ package protect.card_locker;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Outline;
@@ -84,7 +85,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
int loyaltyCardId;
LoyaltyCard loyaltyCard;
boolean rotationEnabled;
DBHelper db;
SQLiteDatabase database;
ImportURIHelper importURIHelper;
Settings settings;
@@ -257,7 +258,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
setContentView(R.layout.loyalty_card_view_layout);
db = new DBHelper(this);
database = new DBHelper(this).getWritableDatabase();
importURIHelper = new ImportURIHelper(this);
coordinatorLayout = findViewById(R.id.coordinator_layout);
@@ -297,7 +298,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
Log.d(TAG, "Scaling to " + scale);
loyaltyCard.zoomLevel = progress;
db.updateLoyaltyCardZoomLevel(loyaltyCardId, loyaltyCard.zoomLevel);
DBHelper.updateLoyaltyCardZoomLevel(database, loyaltyCardId, loyaltyCard.zoomLevel);
setCenterGuideline(loyaltyCard.zoomLevel);
@@ -466,7 +467,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
window.setAttributes(attributes);
}
loyaltyCard = db.getLoyaltyCard(loyaltyCardId);
loyaltyCard = DBHelper.getLoyaltyCard(database, loyaltyCardId);
if (loyaltyCard == null) {
Log.w(TAG, "Could not lookup loyalty card " + loyaltyCardId);
Toast.makeText(this, R.string.noCardExistsError, Toast.LENGTH_LONG).show();
@@ -493,7 +494,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
noteView.setVisibility(View.GONE);
}
List<Group> loyaltyCardGroups = db.getLoyaltyCardGroups(loyaltyCardId);
List<Group> loyaltyCardGroups = DBHelper.getLoyaltyCardGroups(database, loyaltyCardId);
if (loyaltyCardGroups.size() > 0) {
List<String> groupNames = new ArrayList<>();
@@ -640,7 +641,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
// restore bottomSheet UI states from changing orientation
changeUiToBottomSheetState(bottomSheetState);
db.updateLoyaltyCardLastUsed(loyaltyCard.id);
DBHelper.updateLoyaltyCardLastUsed(database, loyaltyCard.id);
}
@Override
@@ -665,7 +666,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
item.setVisible(false);
}
loyaltyCard = db.getLoyaltyCard(loyaltyCardId);
loyaltyCard = DBHelper.getLoyaltyCard(database, loyaltyCardId);
starred = loyaltyCard.starStatus != 0;
menu.findItem(R.id.action_share).setIcon(getIcon(R.drawable.ic_share_white, backgroundNeedsDarkIcons));
@@ -716,7 +717,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
case R.id.action_star_unstar:
starred = !starred;
db.updateLoyaltyCardStarStatus(loyaltyCardId, starred ? 1 : 0);
DBHelper.updateLoyaltyCardStarStatus(database, loyaltyCardId, starred ? 1 : 0);
invalidateOptionsMenu();
return true;
}

View File

@@ -8,6 +8,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.CursorIndexOutOfBoundsException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
@@ -41,7 +42,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
private static final String TAG = "Catima";
public static final String RESTART_ACTIVITY_INTENT = "restart_activity_intent";
private final DBHelper mDB = new DBHelper(this);
private SQLiteDatabase mDatabase;
private LoyaltyCardCursorAdapter mAdapter;
private ActionMode mCurrentActionMode;
private SearchView mSearchView;
@@ -144,7 +145,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
for (LoyaltyCard loyaltyCard : mAdapter.getSelectedItems()) {
Log.e(TAG, "Deleting card: " + loyaltyCard.id);
db.deleteLoyaltyCard(MainActivity.this, loyaltyCard.id);
DBHelper.deleteLoyaltyCard(mDatabase, MainActivity.this, loyaltyCard.id);
ShortcutHelper.removeShortcut(MainActivity.this, loyaltyCard.id);
}
@@ -182,6 +183,8 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = new DBHelper(this).getWritableDatabase();
TabLayout groupsTabLayout = findViewById(R.id.groups);
groupsTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
@@ -365,9 +368,9 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
group = (Group) mGroup;
}
mAdapter.swapCursor(mDB.getLoyaltyCardCursor(mFilter, group, mOrder, mOrderDirection));
mAdapter.swapCursor(DBHelper.getLoyaltyCardCursor(mDatabase, mFilter, group, mOrder, mOrderDirection));
if (mDB.getLoyaltyCardCount() > 0) {
if (DBHelper.getLoyaltyCardCount(mDatabase) > 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
@@ -401,9 +404,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
}
public void updateTabGroups(TabLayout groupsTabLayout) {
final DBHelper db = new DBHelper(this);
List<Group> newGroups = db.getGroups();
List<Group> newGroups = DBHelper.getGroups(mDatabase);
if (newGroups.size() == 0) {
groupsTabLayout.removeAllTabs();

View File

@@ -2,6 +2,7 @@ package protect.card_locker;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
@@ -25,7 +26,7 @@ import androidx.recyclerview.widget.RecyclerView;
public class ManageGroupActivity extends CatimaAppCompatActivity implements ManageGroupCursorAdapter.CardAdapterListener {
private final DBHelper mDB = new DBHelper(this);
private SQLiteDatabase mDatabase;
private ManageGroupCursorAdapter mAdapter;
private final String SAVE_INSTANCE_ADAPTER_STATE = "adapterState";
@@ -45,6 +46,8 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = new DBHelper(this).getWritableDatabase();
mHelpText = findViewById(R.id.helpText);
mCardList = findViewById(R.id.list);
FloatingActionButton saveButton = findViewById(R.id.fabSave);
@@ -70,7 +73,7 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana
return;
}
if (!mGroup._id.equals(currentGroupName)) {
if (mDB.getGroup(currentGroupName) != null) {
if (DBHelper.getGroup(mDatabase, currentGroupName) != null) {
mGroupNameNotInUse = false;
mGroupNameText.setError(getResources().getText(R.string.group_name_already_in_use));
} else {
@@ -86,7 +89,7 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana
throw (new IllegalArgumentException("this activity expects a group loaded into it's intent"));
}
Log.d("groupId", "groupId: " + groupId);
mGroup = mDB.getGroup(groupId);
mGroup = DBHelper.getGroup(mDatabase, groupId);
if (mGroup == null) {
throw (new IllegalArgumentException("cannot load group " + groupId + " from database"));
}
@@ -123,7 +126,7 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana
mAdapter.commitToDatabase();
if (!currentGroupName.equals(mGroup._id)) {
mDB.updateGroup(mGroup._id, currentGroupName);
DBHelper.updateGroup(mDatabase, mGroup._id, currentGroupName);
}
Toast.makeText(getApplicationContext(), R.string.group_updated, Toast.LENGTH_SHORT).show();
finish();
@@ -163,7 +166,7 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana
}
private void updateLoyaltyCardList() {
mAdapter.swapCursor(mDB.getLoyaltyCardCursor());
mAdapter.swapCursor(DBHelper.getLoyaltyCardCursor(mDatabase));
if (mAdapter.getItemCount() == 0) {
mCardList.setVisibility(View.GONE);

View File

@@ -2,6 +2,7 @@ package protect.card_locker;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.HashMap;
import java.util.List;
@@ -13,13 +14,13 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter {
private HashMap<Integer, Boolean> mIsLoyaltyCardInGroupCache;
private HashMap<Integer, List<Group>> mGetGroupCache;
final private Group mGroup;
final private DBHelper mDb;
final private SQLiteDatabase mDatabase;
public ManageGroupCursorAdapter(Context inputContext, Cursor inputCursor, CardAdapterListener inputListener, Group group) {
super(inputContext, inputCursor, inputListener);
mGroup = new Group(group._id, group.order);
mInGroupOverlay = new HashMap<>();
mDb = new DBHelper(inputContext);
mDatabase = new DBHelper(inputContext).getWritableDatabase();
}
@Override
@@ -47,7 +48,7 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter {
if (cache != null) {
return cache;
}
List<Group> groups = mDb.getLoyaltyCardGroups(cardId);
List<Group> groups = DBHelper.getLoyaltyCardGroups(mDatabase, cardId);
mGetGroupCache.put(cardId, groups);
return groups;
}
@@ -94,7 +95,7 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter {
} else {
groups.remove(mGroup);
}
mDb.setLoyaltyCardGroups(cardId, groups);
DBHelper.setLoyaltyCardGroups(mDatabase, cardId, groups);
}
}

View File

@@ -3,6 +3,7 @@ package protect.card_locker;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
@@ -26,7 +27,7 @@ import androidx.recyclerview.widget.RecyclerView;
public class ManageGroupsActivity extends CatimaAppCompatActivity implements GroupCursorAdapter.GroupAdapterListener {
private static final String TAG = "Catima";
private final DBHelper mDb = new DBHelper(this);
private SQLiteDatabase mDatabase;
private TextView mHelpText;
private RecyclerView mGroupList;
GroupCursorAdapter mAdapter;
@@ -42,6 +43,8 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
mDatabase = new DBHelper(this).getWritableDatabase();
}
@Override
@@ -72,9 +75,9 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
}
private void updateGroupList() {
mAdapter.swapCursor(mDb.getGroupCursor());
mAdapter.swapCursor(DBHelper.getGroupCursor(mDatabase));
if (mDb.getGroupCount() == 0) {
if (DBHelper.getGroupCount(mDatabase) == 0) {
mGroupList.setVisibility(View.GONE);
mHelpText.setVisibility(View.VISIBLE);
@@ -118,11 +121,11 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
Toast.makeText(getApplicationContext(), R.string.group_name_is_empty, Toast.LENGTH_SHORT).show();
return;
}
if (mDb.getGroup(inputString) != null) {
if (DBHelper.getGroup(mDatabase, inputString) != null) {
Toast.makeText(getApplicationContext(), R.string.group_name_already_in_use, Toast.LENGTH_SHORT).show();
return;
}
mDb.insertGroup(inputString);
DBHelper.insertGroup(mDatabase, inputString);
updateGroupList();
});
builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel());
@@ -138,10 +141,10 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
}
private void moveGroup(View view, boolean up) {
List<Group> groups = mDb.getGroups();
List<Group> groups = DBHelper.getGroups(mDatabase);
final String groupName = getGroupName(view);
int currentIndex = mDb.getGroup(groupName).order;
int currentIndex = DBHelper.getGroup(mDatabase, groupName).order;
int newIndex;
// Reinsert group in correct position
@@ -160,7 +163,7 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
groups.add(newIndex, group);
// Update database
mDb.reorderGroups(groups);
DBHelper.reorderGroups(mDatabase, groups);
// Update UI
updateGroupList();
@@ -195,7 +198,7 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
builder.setMessage(groupName);
builder.setPositiveButton(getString(R.string.ok), (dialog, which) -> {
mDb.deleteGroup(groupName);
DBHelper.deleteGroup(mDatabase, groupName);
updateGroupList();
// Delete may change ordering, so invalidate
invalidateHomescreenActiveTab();

View File

@@ -2,6 +2,7 @@ package protect.card_locker;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
@@ -45,7 +46,7 @@ class ShortcutHelper {
static void updateShortcuts(Context context, LoyaltyCard card) {
LinkedList<ShortcutInfoCompat> list = new LinkedList<>(ShortcutManagerCompat.getDynamicShortcuts(context));
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase database = new DBHelper(context).getReadableDatabase();
String shortcutId = Integer.toString(card.id);
@@ -88,7 +89,7 @@ class ShortcutHelper {
for (int index = 0; index < list.size(); index++) {
ShortcutInfoCompat prevShortcut = list.get(index);
LoyaltyCard loyaltyCard = dbHelper.getLoyaltyCard(Integer.parseInt(prevShortcut.getId()));
LoyaltyCard loyaltyCard = DBHelper.getLoyaltyCard(database, Integer.parseInt(prevShortcut.getId()));
ShortcutInfoCompat updatedShortcut = createShortcutBuilder(context, loyaltyCard)
.setRank(index)

View File

@@ -2,6 +2,7 @@ package protect.card_locker.importexport;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import net.lingala.zip4j.io.outputstream.ZipOutputStream;
@@ -31,7 +32,7 @@ import protect.card_locker.Utils;
* format.
*/
public class CatimaExporter implements Exporter {
public void exportData(Context context, DBHelper db, OutputStream output, char[] password) throws IOException, InterruptedException {
public void exportData(Context context, SQLiteDatabase database, OutputStream output, char[] password) throws IOException, InterruptedException {
// Necessary vars
int readLen;
byte[] readBuffer = new byte[InternalZipConstants.BUFF_SIZE];
@@ -48,7 +49,7 @@ public class CatimaExporter implements Exporter {
// Generate CSV
ByteArrayOutputStream catimaOutputStream = new ByteArrayOutputStream();
OutputStreamWriter catimaOutputStreamWriter = new OutputStreamWriter(catimaOutputStream, StandardCharsets.UTF_8);
writeCSV(db, catimaOutputStreamWriter);
writeCSV(database, catimaOutputStreamWriter);
// Add CSV to zip file
ZipParameters csvZipParameters = createZipParameters("catima.csv", password);
@@ -60,7 +61,7 @@ public class CatimaExporter implements Exporter {
zipOutputStream.closeEntry();
// Loop over all cards again
Cursor cardCursor = db.getLoyaltyCardCursor();
Cursor cardCursor = DBHelper.getLoyaltyCardCursor(database);
while (cardCursor.moveToNext()) {
// For each card
LoyaltyCard card = LoyaltyCard.toLoyaltyCard(cardCursor);
@@ -94,7 +95,7 @@ public class CatimaExporter implements Exporter {
return zipParameters;
}
private void writeCSV(DBHelper db, OutputStreamWriter output) throws IOException, InterruptedException {
private void writeCSV(SQLiteDatabase database, OutputStreamWriter output) throws IOException, InterruptedException {
CSVPrinter printer = new CSVPrinter(output, CSVFormat.RFC4180);
// Print the version
@@ -105,7 +106,7 @@ public class CatimaExporter implements Exporter {
// Print the header for groups
printer.printRecord(DBHelper.LoyaltyCardDbGroups.ID);
Cursor groupCursor = db.getGroupCursor();
Cursor groupCursor = DBHelper.getGroupCursor(database);
while (groupCursor.moveToNext()) {
Group group = Group.toGroup(groupCursor);
@@ -136,7 +137,7 @@ public class CatimaExporter implements Exporter {
DBHelper.LoyaltyCardDbIds.STAR_STATUS,
DBHelper.LoyaltyCardDbIds.LAST_USED);
Cursor cardCursor = db.getLoyaltyCardCursor();
Cursor cardCursor = DBHelper.getLoyaltyCardCursor(database);
while (cardCursor.moveToNext()) {
LoyaltyCard card = LoyaltyCard.toLoyaltyCard(cardCursor);
@@ -168,12 +169,12 @@ public class CatimaExporter implements Exporter {
printer.printRecord(DBHelper.LoyaltyCardDbIdsGroups.cardID,
DBHelper.LoyaltyCardDbIdsGroups.groupID);
Cursor cardCursor2 = db.getLoyaltyCardCursor();
Cursor cardCursor2 = DBHelper.getLoyaltyCardCursor(database);
while (cardCursor2.moveToNext()) {
LoyaltyCard card = LoyaltyCard.toLoyaltyCard(cardCursor2);
for (Group group : db.getLoyaltyCardGroups(card.id)) {
for (Group group : DBHelper.getLoyaltyCardGroups(database, card.id)) {
printer.printRecord(card.id, group._id);
}

View File

@@ -40,7 +40,7 @@ import protect.card_locker.ZipUtils;
* A header is expected for the each table showing the names of the columns.
*/
public class CatimaImporter implements Importer {
public void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, InterruptedException {
public void importData(Context context, SQLiteDatabase database, InputStream input, char[] password) throws IOException, FormatException, InterruptedException {
InputStream bufferedInputStream = new BufferedInputStream(input);
bufferedInputStream.mark(100);
@@ -55,7 +55,7 @@ public class CatimaImporter implements Importer {
String fileName = Uri.parse(localFileHeader.getFileName()).getLastPathSegment();
if (fileName.equals("catima.csv")) {
importCSV(context, db, new ByteArrayInputStream(ZipUtils.read(zipInputStream).getBytes(StandardCharsets.UTF_8)));
importCSV(context, database, new ByteArrayInputStream(ZipUtils.read(zipInputStream).getBytes(StandardCharsets.UTF_8)));
} else if (fileName.endsWith(".png")) {
Utils.saveCardImage(context, ZipUtils.readImage(zipInputStream), fileName);
} else {
@@ -66,11 +66,11 @@ public class CatimaImporter implements Importer {
if (!isZipFile) {
// This is not a zip file, try importing as bare CSV
bufferedInputStream.reset();
importCSV(context, db, bufferedInputStream);
importCSV(context, database, bufferedInputStream);
}
}
public void importCSV(Context context, DBHelper db, InputStream input) throws IOException, FormatException, InterruptedException {
public void importCSV(Context context, SQLiteDatabase database, InputStream input) throws IOException, FormatException, InterruptedException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
bufferedReader.mark(100);
@@ -87,10 +87,10 @@ public class CatimaImporter implements Importer {
switch (version) {
case 1:
parseV1(context, db, bufferedReader);
parseV1(context, database, bufferedReader);
break;
case 2:
parseV2(context, db, bufferedReader);
parseV2(context, database, bufferedReader);
break;
default:
throw new FormatException(String.format("No code to parse version %s", version));
@@ -99,15 +99,12 @@ 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, SQLiteDatabase database, 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) {
importLoyaltyCard(context, database, db, record);
importLoyaltyCard(context, database, record);
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
@@ -115,19 +112,12 @@ public class CatimaImporter implements Importer {
}
parser.close();
database.setTransactionSuccessful();
} catch (IllegalArgumentException | IllegalStateException e) {
throw new FormatException("Issue parsing CSV data", e);
} finally {
database.endTransaction();
database.close();
}
}
public void parseV2(Context context, DBHelper db, BufferedReader input) throws IOException, FormatException, InterruptedException {
SQLiteDatabase database = db.getWritableDatabase();
database.beginTransaction();
public void parseV2(Context context, SQLiteDatabase database, BufferedReader input) throws IOException, FormatException, InterruptedException {
Integer part = 0;
String stringPart = "";
@@ -145,7 +135,7 @@ public class CatimaImporter implements Importer {
break;
case 1:
try {
parseV2Groups(db, database, stringPart);
parseV2Groups(database, stringPart);
sectionParsed = true;
} catch (FormatException e) {
// We may have a multiline field, try again
@@ -153,7 +143,7 @@ public class CatimaImporter implements Importer {
break;
case 2:
try {
parseV2Cards(context, db, database, stringPart);
parseV2Cards(context, database, stringPart);
sectionParsed = true;
} catch (FormatException e) {
// We may have a multiline field, try again
@@ -161,7 +151,7 @@ public class CatimaImporter implements Importer {
break;
case 3:
try {
parseV2CardGroups(db, database, stringPart);
parseV2CardGroups(database, stringPart);
sectionParsed = true;
} catch (FormatException e) {
// We may have a multiline field, try again
@@ -185,16 +175,12 @@ public class CatimaImporter implements Importer {
stringPart += tmp + "\n";
}
}
database.setTransactionSuccessful();
} catch (FormatException e) {
throw new FormatException("Issue parsing CSV data", e);
} finally {
database.endTransaction();
database.close();
}
}
public void parseV2Groups(DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException {
public void parseV2Groups(SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException {
// Parse groups
final CSVParser groupParser = new CSVParser(new StringReader(data), CSVFormat.RFC4180.builder().setHeader().build());
@@ -215,11 +201,11 @@ public class CatimaImporter implements Importer {
}
for (CSVRecord record : records) {
importGroup(database, db, record);
importGroup(database, record);
}
}
public void parseV2Cards(Context context, DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException {
public void parseV2Cards(Context context, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException {
// Parse cards
final CSVParser cardParser = new CSVParser(new StringReader(data), CSVFormat.RFC4180.builder().setHeader().build());
@@ -240,11 +226,11 @@ public class CatimaImporter implements Importer {
}
for (CSVRecord record : records) {
importLoyaltyCard(context, database, db, record);
importLoyaltyCard(context, database, record);
}
}
public void parseV2CardGroups(DBHelper db, SQLiteDatabase database, String data) throws IOException, FormatException, InterruptedException {
public void parseV2CardGroups(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());
@@ -265,7 +251,7 @@ public class CatimaImporter implements Importer {
}
for (CSVRecord record : records) {
importCardGroupMapping(database, db, record);
importCardGroupMapping(database, record);
}
}
@@ -273,7 +259,7 @@ public class CatimaImporter implements Importer {
* Import a single loyalty card into the database using the given
* session.
*/
private void importLoyaltyCard(Context context, SQLiteDatabase database, DBHelper helper, CSVRecord record)
private void importLoyaltyCard(Context context, SQLiteDatabase database, CSVRecord record)
throws IOException, FormatException {
int id = CSVHelpers.extractInt(DBHelper.LoyaltyCardDbIds.ID, record, false);
@@ -343,31 +329,29 @@ public class CatimaImporter implements Importer {
// We catch this exception so we can still import old backups
}
helper.insertLoyaltyCard(database, id, store, note, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, starStatus, lastUsed);
DBHelper.insertLoyaltyCard(database, id, store, note, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, starStatus, lastUsed);
}
/**
* Import a single group into the database using the given
* session.
*/
private void importGroup(SQLiteDatabase database, DBHelper helper, CSVRecord record)
throws IOException, FormatException {
private void importGroup(SQLiteDatabase database, CSVRecord record) throws FormatException {
String id = CSVHelpers.extractString(DBHelper.LoyaltyCardDbGroups.ID, record, null);
helper.insertGroup(database, id);
DBHelper.insertGroup(database, id);
}
/**
* Import a single card to group mapping into the database using the given
* session.
*/
private void importCardGroupMapping(SQLiteDatabase database, DBHelper helper, CSVRecord record)
throws IOException, FormatException {
private void importCardGroupMapping(SQLiteDatabase database, CSVRecord record) throws FormatException {
Integer cardId = CSVHelpers.extractInt(DBHelper.LoyaltyCardDbIdsGroups.cardID, record, false);
String groupId = CSVHelpers.extractString(DBHelper.LoyaltyCardDbIdsGroups.groupID, record, null);
List<Group> cardGroups = helper.getLoyaltyCardGroups(cardId);
cardGroups.add(helper.getGroup(groupId));
helper.setLoyaltyCardGroups(database, cardId, cardGroups);
List<Group> cardGroups = DBHelper.getLoyaltyCardGroups(database, cardId);
cardGroups.add(DBHelper.getGroup(database, groupId));
DBHelper.setLoyaltyCardGroups(database, cardId, cardGroups);
}
}

View File

@@ -1,6 +1,7 @@
package protect.card_locker.importexport;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import java.io.IOException;
import java.io.OutputStream;
@@ -17,5 +18,5 @@ public interface Exporter {
*
* @throws IOException
*/
void exportData(Context context, DBHelper db, OutputStream output, char[] password) throws IOException, InterruptedException;
void exportData(Context context, SQLiteDatabase database, OutputStream output, char[] password) throws IOException, InterruptedException;
}

View File

@@ -30,7 +30,7 @@ import protect.card_locker.FormatException;
* A header is expected for the each table showing the names of the columns.
*/
public class FidmeImporter implements Importer {
public void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException {
public void importData(Context context, SQLiteDatabase database, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException {
// We actually retrieve a .zip file
ZipInputStream zipInputStream = new ZipInputStream(input, password);
@@ -52,14 +52,11 @@ public class FidmeImporter implements Importer {
throw new FormatException("Couldn't find loyalty_programs.csv in zip file or it is empty");
}
SQLiteDatabase database = db.getWritableDatabase();
database.beginTransaction();
final CSVParser fidmeParser = new CSVParser(new StringReader(loyaltyCards.toString()), CSVFormat.RFC4180.builder().setDelimiter(';').setHeader().build());
try {
for (CSVRecord record : fidmeParser) {
importLoyaltyCard(database, db, record);
importLoyaltyCard(database, record);
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
@@ -71,10 +68,6 @@ public class FidmeImporter implements Importer {
fidmeParser.close();
}
database.setTransactionSuccessful();
database.endTransaction();
database.close();
zipInputStream.close();
}
@@ -82,8 +75,8 @@ public class FidmeImporter implements Importer {
* Import a single loyalty card into the database using the given
* session.
*/
private void importLoyaltyCard(SQLiteDatabase database, DBHelper helper, CSVRecord record)
throws IOException, FormatException {
private void importLoyaltyCard(SQLiteDatabase database, CSVRecord record)
throws FormatException {
// A loyalty card export from Fidme contains the following fields:
// Retailer (store name)
// Program (program name)
@@ -129,6 +122,6 @@ public class FidmeImporter implements Importer {
// TODO: Front and back image
helper.insertLoyaltyCard(database, store, note, null, BigDecimal.valueOf(0), null, cardId, null, barcodeType, null, starStatus, null);
DBHelper.insertLoyaltyCard(database, store, note, null, BigDecimal.valueOf(0), null, cardId, null, barcodeType, null, starStatus, null);
}
}

View File

@@ -1,6 +1,7 @@
package protect.card_locker.importexport;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import org.json.JSONException;
@@ -8,7 +9,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import protect.card_locker.DBHelper;
import protect.card_locker.FormatException;
/**
@@ -23,5 +23,5 @@ public interface Importer {
* @throws IOException
* @throws FormatException
*/
void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, InterruptedException, JSONException, ParseException;
void importData(Context context, SQLiteDatabase database, InputStream input, char[] password) throws IOException, FormatException, InterruptedException, JSONException, ParseException;
}

View File

@@ -1,6 +1,7 @@
package protect.card_locker.importexport;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.io.IOException;
@@ -21,7 +22,7 @@ public class MultiFormatExporter {
* 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, SQLiteDatabase database, OutputStream output, DataFormat format, char[] password) {
Exporter exporter = null;
switch (format) {
@@ -35,7 +36,7 @@ public class MultiFormatExporter {
if (exporter != null) {
try {
exporter.exportData(context, db, output, password);
exporter.exportData(context, database, output, password);
return ImportExportResult.Success;
} catch (IOException e) {
Log.e(TAG, "Failed to export data", e);

View File

@@ -1,6 +1,7 @@
package protect.card_locker.importexport;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import net.lingala.zip4j.exception.ZipException;
@@ -28,7 +29,7 @@ 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, SQLiteDatabase database, InputStream input, DataFormat format, char[] password) {
Importer importer = null;
switch (format) {
@@ -47,15 +48,18 @@ public class MultiFormatImporter {
}
if (importer != null) {
database.beginTransaction();
try {
importer.importData(context, db, input, password);
importer.importData(context, database, input, password);
database.setTransactionSuccessful();
return ImportExportResult.Success;
} catch (ZipException e) {
return ImportExportResult.BadPassword;
} catch (IOException | FormatException | InterruptedException | JSONException | ParseException | NullPointerException e) {
Log.e(TAG, "Failed to import data", e);
} finally {
database.endTransaction();
}
} else {
Log.e(TAG, "Unsupported data format imported: " + format.name());
}

View File

@@ -39,7 +39,7 @@ import protect.card_locker.ZipUtils;
* A header is expected for the each table showing the names of the columns.
*/
public class StocardImporter implements Importer {
public void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException {
public void importData(Context context, SQLiteDatabase database, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException {
HashMap<String, HashMap<String, Object>> loyaltyCardHashMap = new HashMap<>();
HashMap<String, HashMap<String, String>> providers = new HashMap<>();
@@ -153,9 +153,6 @@ public class StocardImporter implements Importer {
throw new FormatException("Couldn't find any loyalty cards in this Stocard export.");
}
SQLiteDatabase database = db.getWritableDatabase();
database.beginTransaction();
for (HashMap<String, Object> loyaltyCardData : loyaltyCardHashMap.values()) {
String providerId = (String) loyaltyCardData.get("_providerId");
HashMap<String, String> providerData = providers.get(providerId);
@@ -173,7 +170,7 @@ public class StocardImporter implements Importer {
}
}
long loyaltyCardInternalId = db.insertLoyaltyCard(database, store, note, null, BigDecimal.valueOf(0), null, cardId, null, barcodeType, null, 0, null);
long loyaltyCardInternalId = DBHelper.insertLoyaltyCard(database, store, note, null, BigDecimal.valueOf(0), null, cardId, null, barcodeType, null, 0, null);
if (loyaltyCardData.containsKey("frontImage")) {
Utils.saveCardImage(context, (Bitmap) loyaltyCardData.get("frontImage"), (int) loyaltyCardInternalId, ImageLocationType.front);
@@ -183,10 +180,6 @@ public class StocardImporter implements Importer {
}
}
database.setTransactionSuccessful();
database.endTransaction();
database.close();
zipInputStream.close();
}

View File

@@ -36,7 +36,7 @@ import protect.card_locker.Utils;
* A header is expected for the each table showing the names of the columns.
*/
public class VoucherVaultImporter implements Importer {
public void importData(Context context, DBHelper db, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException {
public void importData(Context context, SQLiteDatabase database, InputStream input, char[] password) throws IOException, FormatException, JSONException, ParseException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
@@ -46,9 +46,6 @@ public class VoucherVaultImporter implements Importer {
}
JSONArray jsonArray = new JSONArray(sb.toString());
SQLiteDatabase database = db.getWritableDatabase();
database.beginTransaction();
// See https://github.com/tim-smart/vouchervault/issues/4#issuecomment-788226503 for more info
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonCard = jsonArray.getJSONObject(i);
@@ -129,13 +126,9 @@ public class VoucherVaultImporter implements Importer {
throw new FormatException("Unknown colour type found: " + colorFromJSON);
}
db.insertLoyaltyCard(store, "", expiry, balance, balanceType, cardId, null, barcodeType, headerColor, 0, Utils.getUnixTime());
DBHelper.insertLoyaltyCard(database, store, "", expiry, balance, balanceType, cardId, null, barcodeType, headerColor, 0, Utils.getUnixTime());
}
database.setTransactionSuccessful();
database.endTransaction();
database.close();
bufferedReader.close();
}
}