Reputation: 61
I have a method like that
private void addDataToDailyStatisticsIncome(String date, String money, int idUser){
Cursor res1 = db.getDataTableDailyStatistic(idUser);
int temp = 0;
int money1, money2;
res1.moveToFirst();
while (res1.moveToNext()) {
if (date.equals(res1.getString(1)) == true) {
temp = 1;
break;
} else {
temp = 0;
}
}
if(temp == 1){
money1 = Integer.parseInt(res1.getString(3));
money2 = Integer.parseInt(money);
money1 = money1 + money2;
long isUpdated = db.updateTableDailyStatistic(res1.getString(1), Integer.toString(money1), idUser, Integer.parseInt(res1.getString(0)));
} else{
long isInserted = db.insertTableDailyStatistic(date, money, idUser);
}
}
I want to check when new data insert to app. If "date
" is available, i will update "money
" in same date.
Or if "date
" is not available, i will insert new Date
with Money
.
But i have 1 problem that it always inserts, it never updates although i have a same Date
in Database
.
Can you help me fix this problem?
Upvotes: 2
Views: 112
Reputation: 1579
Follow these steps:
Check if date
is available and get money1
:
int money1 = 0;
boolean isAvailable = false;
String query = "select count(*) from TableName where date = ?";
Cursor cursor = db.rawQuery(query, new String[] {date});
if (cursor != null && cursor.moveToFirst()) {
isAvailable = true;
money1 = cursor.getInt(money1_column);
cursor.close();
}
Insert or Update row:
if (isAvailable) {
// update
} else {
// insert
}
Upvotes: 1
Reputation: 1078
You can do it by declaring date as primary key. Write both sql query (insert and update ) in the the above method.
Upvotes: 0