public class SingletonDbHelper {
private MultiThreadSQLiteOpenHelper dbHelper;
public static final SingletonDbHelper INSTANCE = new SingletonDbHelper();
private SingletonDbHelper() {
}
public SQLiteDatabase open(Context context) {
synchronized (this) {
//Logger.INSTANCE.debug(TAG, "asking for opening");
if (dbHelper == null) {
dbHelper = new DBHelper(context);
}
return dbHelper.getWritableDatabase();
}
}
public void close() {
synchronized (this) {
//Logger.INSTANCE.debug(TAG, "asking for closing");
if (dbHelper != null) {
// Ask for closing database
if (dbHelper.closeIfNeeded()) {
dbHelper = null;
}
}
}
}
}
public class TableCostProvider {
// ...
public static double getAllCostSum(Context context) {
SQLiteDatabase db = SingletonDbHelper.INSTANCE.open(context
.getApplicationContext());
// Достаем все результаты, и группируем их по валютам
Cursor c = db.query(DBHelper.table_cost, new String[] {
DBHelper.cost_currency, "SUM(" + DBHelper.cost_sum + ")" },
null, null, DBHelper.cost_currency, null, null);
double value = .0;
while (c.moveToNext()) {
int currencyId = c.getInt(0);
double sum = c.getDouble(1);
// получаем валюту
Cursor currencyCur = db.query(DBHelper.table_currency,
new String[] { DBHelper.currency_rate },
DBHelper.currency_id + "=" + currencyId, null, null, null, null);
if (currencyCur.moveToFirst()) {
value += sum / currencyCur.getDouble(0);
}
currencyCur.close();
}
SingletonDbHelper.INSTANCE.close();
c.close();
return value;
}
// ...
}
@Override
protected void onResume() {
//...
fillData();
//...
}
void fillData() {
//...
double sumCost = TableCostProvider.getAllCostSum(this);
}
public class TableCostProvider {
public static long addCost(Context context, Date date, int category,
double sum, int currency, String comment) {
SQLiteDatabase sqdb = SingletonDbHelper.INSTANCE.open(context
.getApplicationContext());
ContentValues row = new ContentValues();
row.put(DBHelper.cost_datetime, date.getTime());
row.put(DBHelper.cost_category, category);
row.put(DBHelper.cost_sum, sum);
row.put(DBHelper.cost_currency, currency);
row.put(DBHelper.cost_comment, comment);
long d = sqdb.insert(DBHelper.table_cost, null, row);
SingletonDbHelper.INSTANCE.close();
return d;
}
}
public static long addCost(Context context, Date date, int category, double sum, int currency, String comment) {
SQLiteDatabase sqdb = SingletonDbHelper.INSTANCE.open(context
.getApplicationContext());
ContentValues row = new ContentValues();
row.put(DBHelper.cost_datetime, date.getTime());
row.put(DBHelper.cost_category, category);
row.put(DBHelper.cost_sum, sum);
row.put(DBHelper.cost_currency, currency);
row.put(DBHelper.cost_comment, comment);
long d = sqdb.insert(DBHelper.table_cost, null, row);
SingletonDbHelper.INSTANCE.close();
return d;
}