问题
I have a user who has a starting value for their credits set at '5'. Now I want to create a method which will allow the user to add on to that number, e.g. 2. This will then update the row in the database column to become 7.
However I cant get my current method to do this.
Current method:
public void upDateUser(String money)
{
String selectQuery = "SELECT " + KEY_CREDITS + " from " +
DATABASE_TABLE + " where " + KEY_ROWID + " = " + 0;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
int oldMoney = 0;
if (c.moveToFirst())
{
oldMoney = Integer.parseInt(c.getString(4));
}
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, (oldMoney + money));
String filter = KEY_ROWID + "=" + 0;
db.update(DATABASE_TABLE, cvUpdate, filter, null);
}
I then call the above method in an another activity:
public void onClick(View arg0)
{
switch (arg0.getId()){
case R.id.topup:
boolean work = true;
try{
String money = spinner.getSelectedItem().toString();
UDbHelper ud = new UDbHelper(this);
ud.open();
ud.upDateUser(money);
ud.close();
回答1:
Change the following step to get the value of oldmoney
oldMoney = c.getInt(c.getColumnIndex(KEY_CREDITS));
Also you cannot add strings to get an integer total value. So convert the value money to integer before finding the total
int money =Integer.parseInt(money);
If you have a string data type for KEY_CREDITS column then after finding the total you should convert it back to string before updating
cvUpdate.put(KEY_CREDITS, String.valueOf(oldMoney + money));
来源:https://stackoverflow.com/questions/23047462/adding-on-to-the-current-value-sqlite