Cleanup: use try-with-resources.

This commit is contained in:
Dennis Guse
2025-12-06 08:23:02 +01:00
parent 1cb3db496a
commit 7cb97b0e6b
4 changed files with 49 additions and 59 deletions
@@ -100,18 +100,18 @@ public class CustomSQLiteOpenHelperTest {
// Open database with SQL upgrade // Open database with SQL upgrade
Map<String, String> tableByUpgrade; Map<String, String> tableByUpgrade;
Map<String, String> indicesByUpgrade; Map<String, String> indicesByUpgrade;
try (SQLiteDatabase dbUpgraded = new CustomSQLiteOpenHelper(context, DATABASE_NAME).getReadableDatabase()) { try (CustomSQLiteOpenHelper dbUpgraded = new CustomSQLiteOpenHelper(context, DATABASE_NAME)) {
tableByUpgrade = getSQL(dbUpgraded, "table"); tableByUpgrade = getSQL(dbUpgraded.getReadableDatabase(), "table");
indicesByUpgrade = getSQL(dbUpgraded, "index"); indicesByUpgrade = getSQL(dbUpgraded.getReadableDatabase(), "index");
} }
context.deleteDatabase(DATABASE_NAME); context.deleteDatabase(DATABASE_NAME);
// Open database via creation script // Open database via creation script
Map<String, String> tablesByCreate; Map<String, String> tablesByCreate;
Map<String, String> indicesByCreate; Map<String, String> indicesByCreate;
try (SQLiteDatabase dbCreated = new CustomSQLiteOpenHelper(context, DATABASE_NAME).getReadableDatabase()) { try (CustomSQLiteOpenHelper dbCreated = new CustomSQLiteOpenHelper(context, DATABASE_NAME)) {
tablesByCreate = getSQL(dbCreated, "table"); tablesByCreate = getSQL(dbCreated.getReadableDatabase(), "table");
indicesByCreate = getSQL(dbCreated, "index"); indicesByCreate = getSQL(dbCreated.getReadableDatabase(), "index");
} }
@@ -134,14 +134,16 @@ public class CustomSQLiteOpenHelperTest {
@Test @Test
public void onDowngrade_ToVersion23() { public void onDowngrade_ToVersion23() {
// Create most recent database schema // Create most recent database schema
new CustomSQLiteOpenHelper(context, DATABASE_NAME).getReadableDatabase().close(); try(CustomSQLiteOpenHelper db = new CustomSQLiteOpenHelper(context, DATABASE_NAME)) {
db.getReadableDatabase();
}
// Downgrade schema to version 23 (base version) // Downgrade schema to version 23 (base version)
Map<String, String> tablesByDowngrade; Map<String, String> tablesByDowngrade;
Map<String, String> indicesByDowngrade; Map<String, String> indicesByDowngrade;
try (SQLiteDatabase db = new CustomSQLiteOpenHelper(context, DATABASE_NAME, 23).getReadableDatabase()) { try (CustomSQLiteOpenHelper db = new CustomSQLiteOpenHelper(context, DATABASE_NAME, 23)) {
tablesByDowngrade = getSQL(db, "table"); tablesByDowngrade = getSQL(db.getReadableDatabase(), "table");
indicesByDowngrade = getSQL(db, "index"); indicesByDowngrade = getSQL(db.getReadableDatabase(), "index");
} }
// then - verify table structure // then - verify table structure
@@ -155,9 +157,9 @@ public class CustomSQLiteOpenHelperTest {
@Test @Test
public void track_uuid_unique() { public void track_uuid_unique() {
try (SQLiteDatabase db = new CustomSQLiteOpenHelper(context, DATABASE_NAME).getWritableDatabase()) { try (CustomSQLiteOpenHelper db = new CustomSQLiteOpenHelper(context, DATABASE_NAME)) {
db.execSQL("INSERT INTO tracks (uuid) VALUES (0x00)"); db.getWritableDatabase().execSQL("INSERT INTO tracks (uuid) VALUES (0x00)");
db.execSQL("INSERT INTO tracks (uuid) VALUES (0x00)"); db.getWritableDatabase().execSQL("INSERT INTO tracks (uuid) VALUES (0x00)");
fail("unique constraint not enforced"); fail("unique constraint not enforced");
} catch (SQLiteConstraintException e) { } catch (SQLiteConstraintException e) {
assertTrue(e.getMessage().contains("UNIQUE constraint failed: tracks.uuid")); assertTrue(e.getMessage().contains("UNIQUE constraint failed: tracks.uuid"));
@@ -168,7 +170,8 @@ public class CustomSQLiteOpenHelperTest {
public void upgrade_data_to_30() { public void upgrade_data_to_30() {
// given: a track in version 29 // given: a track in version 29
createVersion23(); createVersion23();
try (SQLiteDatabase db29 = new CustomSQLiteOpenHelper(context, DATABASE_NAME, 29).getWritableDatabase()) { try (CustomSQLiteOpenHelper db = new CustomSQLiteOpenHelper(context, DATABASE_NAME, 29)) {
SQLiteDatabase db29 = db.getWritableDatabase();
db29.beginTransaction(); db29.beginTransaction();
db29.execSQL("INSERT INTO tracks (_id) VALUES (1)"); db29.execSQL("INSERT INTO tracks (_id) VALUES (1)");
@@ -201,7 +204,8 @@ public class CustomSQLiteOpenHelperTest {
} }
// when / then // when / then
try (SQLiteDatabase db30 = new CustomSQLiteOpenHelper(context, DATABASE_NAME, 30).getWritableDatabase()) { try (CustomSQLiteOpenHelper db = new CustomSQLiteOpenHelper(context, DATABASE_NAME, 30)) {
SQLiteDatabase db30 = db.getWritableDatabase();
{ {
// Track 1 // Track 1
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
@@ -261,7 +265,7 @@ public class CustomSQLiteOpenHelperTest {
private void createVersion23() { private void createVersion23() {
// Manually create database schema with version 23 (base version) // Manually create database schema with version 23 (base version)
SQLiteDatabase dbBase = new SQLiteOpenHelper(context, DATABASE_NAME, null, 23) { try(SQLiteOpenHelper dbBase = new SQLiteOpenHelper(context, DATABASE_NAME, null, 23) {
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
} }
@@ -269,12 +273,10 @@ public class CustomSQLiteOpenHelperTest {
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
} }
}.getWritableDatabase(); }) {
dbBase.getWritableDatabase().execSQL(TRACKS_CREATE_TABLE_V23);
dbBase.execSQL(TRACKS_CREATE_TABLE_V23); dbBase.getWritableDatabase().execSQL(TRACKPOINTS_CREATE_TABLE_V23);
dbBase.execSQL(TRACKPOINTS_CREATE_TABLE_V23); dbBase.getWritableDatabase().execSQL(WAYPOINTS_CREATE_TABLE_V23);
dbBase.execSQL(WAYPOINTS_CREATE_TABLE_V23); }
dbBase.close();
} }
} }
@@ -314,19 +314,19 @@ public class GPXTrackImporterTest {
// given // given
XMLImporter importer = new XMLImporter(new GPXTrackImporter(context, trackImporter)); XMLImporter importer = new XMLImporter(new GPXTrackImporter(context, trackImporter));
InputStream inputStream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(de.dennisguse.opentracks.test.R.raw.gpx_timezone); InputStream inputStream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(de.dennisguse.opentracks.test.R.raw.gpx_timezone);
InputStream inputStreamExpected = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(de.dennisguse.opentracks.test.R.raw.gpx_timezone); try(InputStream inputStreamExpected = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(de.dennisguse.opentracks.test.R.raw.gpx_timezone)) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // when
// 1. import
importTrackId = importer.importFile(inputStream).get(0);
Track importedTrack = contentProviderUtils.getTrack(importTrackId);
// when TrackExporter trackExporter = TrackFileFormat.GPX.createTrackExporter(context, contentProviderUtils);
// 1. import trackExporter.writeTrack(List.of(importedTrack), outputStream);
importTrackId = importer.importFile(inputStream).get(0);
Track importedTrack = contentProviderUtils.getTrack(importTrackId);
TrackExporter trackExporter = TrackFileFormat.GPX.createTrackExporter(context, contentProviderUtils); // then
trackExporter.writeTrack(List.of(importedTrack), outputStream); assertEquals(new String(inputStreamExpected.readAllBytes(), StandardCharsets.UTF_8), outputStream.toString());
}
// then
assertEquals(new String(inputStreamExpected.readAllBytes(), StandardCharsets.UTF_8), outputStream.toString());
} }
} }
@@ -42,27 +42,21 @@ public class ThemeUtils {
} }
public static int getFontSizeSmallInPx(Context context) { public static int getFontSizeSmallInPx(Context context) {
TypedArray typedArray = context.obtainStyledAttributes(R.style.TextAppearance_MaterialComponents_Body2, new int[]{android.R.attr.textSize}); try(TypedArray typedArray = context.obtainStyledAttributes(R.style.TextAppearance_MaterialComponents_Body2, new int[]{android.R.attr.textSize})) {
int fontSize = typedArray.getDimensionPixelSize(0, 12); return typedArray.getDimensionPixelSize(0, 12);
typedArray.recycle(); }
return fontSize;
} }
public static int getFontSizeMediumInPx(Context context) { public static int getFontSizeMediumInPx(Context context) {
TypedArray typedArray = context.obtainStyledAttributes(R.style.TextAppearance_MaterialComponents_Body1, new int[]{android.R.attr.textSize}); try(TypedArray typedArray = context.obtainStyledAttributes(R.style.TextAppearance_MaterialComponents_Body1, new int[]{android.R.attr.textSize})) {
int fontSize = typedArray.getDimensionPixelSize(0, 15); return typedArray.getDimensionPixelSize(0, 15);
typedArray.recycle(); }
return fontSize;
} }
/**
* Gets the photo height.
*/
public static int getPhotoHeight(Context context) { public static int getPhotoHeight(Context context) {
int[] attrs = new int[]{android.R.attr.listPreferredItemHeight}; try(TypedArray typeArray = context.obtainStyledAttributes(new int[]{android.R.attr.listPreferredItemHeight})) {
TypedArray typeArray = context.obtainStyledAttributes(attrs); int height = typeArray.getDimensionPixelSize(0, 128);
int height = typeArray.getDimensionPixelSize(0, 128); return 2 * height;
typeArray.recycle(); }
return 2 * height;
} }
} }
@@ -189,16 +189,10 @@ public class FileUtils {
return name; return name;
} }
/**
* Copy a File (src) to a File (dst).
*
* @param src source file.
* @param dst destination file.
*/
public static void copy(FileDescriptor src, File dst) { public static void copy(FileDescriptor src, File dst) {
try (FileChannel in = new FileInputStream(src).getChannel(); try (FileInputStream in = new FileInputStream(src);
FileChannel out = new FileOutputStream(dst).getChannel()) { FileOutputStream out = new FileOutputStream(dst)) {
in.transferTo(0, in.size(), out); in.getChannel().transferTo(0, in.getChannel().size(), out.getChannel());
} catch (Exception e) { } catch (Exception e) {
// post to log // post to log
Log.e(TAG, e.getMessage()); Log.e(TAG, e.getMessage());