How do I add and subtract numbers in SQLite for android?

北战南征 提交于 2019-12-08 05:47:22

问题


I'm creating a simple financial app where the user can input an income or expense. I cannot find anywhere how I can change the "total" amount by adding or subtracting numbers inside the database. The easiest way I can explain it is:

user enters an income of $10 : So I would add that 10 into the database. user enters an expense of -$5 : so i would also add that into the database

the end result should be $5 as the total, but how do I do this?

I'm completely stuck as I've never use SQLite before. Thanks


回答1:


You can do that simply by firing 2 commands on SQL
a) Use Select to get the value from the SQLite Database
b) In Android programming add them or subtract them
c) Update the new Total into the database

public void updateExpense(decimal Expense,String Condition) {
    double current = 0;
    db = this.getReadableDatabase();
    String selectQuery = "select id, total from  " + TABLE_YourTable ;
    Cursor cursor = db.rawQuery(selectQuery, null);
    int RowID=0;
    if (cursor.moveToFirst()) {
            current=  Double.parseDouble(cursor.getString(1));
            RowID= Integer.parseInt(cursor.getString(0));
    }
    /// Now we use condition --> if condition is positive it mean add ... if condition is negative it means 
    ////subtract
    if(Condition.equals("positive"){
            current += Expense;
    }else {
            current =current - Expense; 
    }
    cursor.close();
    db.close();


    //Your Update to SQLite
    db = this.getReadableDatabase();
    ContentValues values = new ContentValues();
    values.put(total , current );

    db.update(TABLE_YourTable , values, KEY_ID + " = ?", new String[] { String.valueOf(RowID) });
    db.close();

}


来源:https://stackoverflow.com/questions/17302548/how-do-i-add-and-subtract-numbers-in-sqlite-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!