如何在SQLite for android中添加和减去数字?

时间:2013-06-25 16:22:29

标签: android sqlite function finance

我正在创建一个简单的财务应用,用户可以输入收入或费用。我无法在任何地方找到如何更改"总计"通过在数据库中添加或减去数字来计算金额。我能解释的最简单的方法是:

用户输入10美元的收入:所以我会将10添加到数据库中。 用户输入 - $ 5的费用:所以我也将其添加到数据库中

最终结果应该是5美元,但我该怎么做?

我完全陷入困境,因为我之前从未使用过SQLite。感谢

1 个答案:

答案 0 :(得分:1)

你可以通过在SQL上发出2个命令来做到这一点 a)使用SelectSQLite数据库中获取值 b)在Android编程中添加或减去它们 c)Update新的总计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();

}