First Of All i am new to programming currently learning Android .And also this is my first Question over here so pardon if any mistake. The thing is i am stucked in how to get total of database column. here's my code to retrieve the data from the sqlite helper.
private void GetColumnTotal() {
SQLHelper ColumnTOtal = new SQLHelper(this);
try {
ColumnTOtal.open();
int total = ColumnTOtal.Total();
ColumnTOtal.close();
RemainingAmount.setText(total);
} catch (SQLException e) {
e.printStackTrace();
}
}
`And heres the code of my sqlite helper . i am posting it all hope you guys help.
public class SQLHelper {
public static final String KEY_ROWID = "_id";
public static final String KEY_MONEY = "SpendedMoney";
private static final String DATABASE_NAME = "BudgetDB";
private static final String DATABASE_TABLE = "BudgetTable";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private SQLiteDatabase ourDATABSE;
private DBHelper ourHelper;
public SQLHelper(Context context) {
ourContext = context;
}
public SQLHelper open() throws SQLException {
ourHelper = new DBHelper(ourContext);
ourDATABSE = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String money) {
ContentValues cv = new ContentValues();
cv.put(KEY_MONEY, money);
return ourDATABSE.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_MONEY};
Cursor c = ourDATABSE.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_MONEY);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " :- " + c.getString(iName) + "\n";
}
return result;
}
public Cursor Total() {
Cursor cur = ourDATABSE.rawQuery("SELECT SUM(SpendedMoney) FROM BudgetTable", null);
if (cur.moveToFirst()) {
}
return cur.getInt(0);
}
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_MONEY + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
}
Aucun commentaire:
Enregistrer un commentaire