Skip to content

Commit

Permalink
add try finally blocks to close the cursor and db anyway
Browse files Browse the repository at this point in the history
  • Loading branch information
mricefox committed Mar 24, 2016
1 parent 75e23ac commit 3b2465f
Showing 1 changed file with 46 additions and 22 deletions.
68 changes: 46 additions & 22 deletions hawk/src/main/java/com/orhanobut/hawk/SqliteStorage.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,15 @@ public SqliteHelper(Context context, String dbName) {

public synchronized boolean put(String key, String value) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME +
" (" + COL_KEY + ", " + COL_VALUE + ") " +
" VALUES('" + key + "', '" + value + "')");
db.close();
try {
db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME +
" (" + COL_KEY + ", " + COL_VALUE + ") " +
" VALUES('" + key + "', '" + value + "')");
} catch (Exception ignored) {
return false;
} finally {
db.close();
}
return true;
}

Expand All @@ -122,9 +127,13 @@ public synchronized boolean put(List<Pair<String, ?>> list) {

public synchronized boolean delete(String key) {
SQLiteDatabase db = this.getWritableDatabase();
int count = db.delete(TABLE_NAME, COL_KEY + "='" + key + "'", null);
db.close();
return count != -1;
int count = 0;
try {
count = db.delete(TABLE_NAME, COL_KEY + "='" + key + "'", null);
} finally {
db.close();
}
return count != 0;
}

public synchronized boolean delete(String... keys) {
Expand Down Expand Up @@ -154,32 +163,47 @@ public synchronized boolean contains(String key) {

public synchronized String get(String key) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +
" WHERE " + COL_KEY + " = '" + key + "'", null);
if (cursor == null) {
return null;
}
cursor.moveToFirst();
if (cursor.getCount() == 0) {
return null;
Cursor cursor = null;
String value = null;
try {
cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +
" WHERE " + COL_KEY + " = '" + key + "'", null);
if (cursor == null) {
return null;
}
if (!cursor.moveToFirst()) {
return null;
}
value = cursor.getString(1);
} finally {
if (cursor != null) {
cursor.close();
}
db.close();
}
String value = cursor.getString(1);
cursor.close();
db.close();
return value;
}

public synchronized boolean clearAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME);
db.close();
try {
db.execSQL("DELETE FROM " + TABLE_NAME);
} catch (Exception ignored) {
return false;
} finally {
db.close();
}
return true;
}

public synchronized long count() {
SQLiteDatabase db = this.getWritableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
long count = 0;
try {
count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
} finally {
db.close();
}
return count;
}
}
Expand Down

0 comments on commit 3b2465f

Please sign in to comment.