how to update new row in android sqlite database - android

Can anybody guide me.
I have an android app. That takes daily user entered value. I want that till same date on same day a user can enter n re-enter values in database , open or close app what ever but value just get updated till same date say for today 22/10/2014.
Now I have once inserted date value in my sqlite database. but if i just update it by user entered value so only one row is created n get updated, even if the date get change the next day.
But if I insert the date again then next row is created that I want actually.
My problem is that : now how to update my sqlite database at most recent date.
My update of user value from a checkbox is going through this method.
public long send(boolean a) {
ContentValues cv = new ContentValues();
cv.put(SEND_Today, a);
return ourDatabase.update(MY_DAILYTABLE, cv, DATE + "=" + "date", null);
it update all the rows as every row contain date column.
I want somthing like this
ourDatabase.update(My_DAILYTABLE , cv , "(select MAX(date) from My_DAILYTABLE )" , null;
update dailydata set daily = 10 where date = (select max(date) from dailydata) // because I know sqlite run this query successfuly
But whatever query I write I get error.
Can anybody guide me a correct query to achieve this functionality. Just need to know the write update query in Android SQLite.

You have to give the entire WHERE clause, that is, also the date =:
ourDatabase.update(My_DAILYTABLE, cv, DATE+" = (select...)", null);

you can follow this:
db.update(DB_TABLE, contentValues, DB_TABLE_ROW_NAME + " = ? ", new String[] { WHERE_DB_TABLE_ROW_VALUE });
should:
ourDatabase.update(MY_DAILYTABLE, cv, DATE + " =? " , new String[] { yourMaxDate });
Or use rawQuery:
String sql = "update dailydata set daily = 10 where date = (select max(date) from dailydata)";
Cursor cursor = db.rawQuery(sql, null);
if (cursor2.moveToFirst()) {
// can get column value as select query
}

Related

How can use sqlite update via ContentValues when want to update depend on current value and how can retrieve the Result?

I've a situation in sqlite that make you an example: My table has two fields,"_id" and "_score" . I have a record with _id=1, _score=10. I want to update this row to 5 number more than the current value(10). in SQL i can do it simple like:
Update my_table set _score = _score + 5 where _id = 1
but in sqlite I have these that I don't know how can fix it to what I want :
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(MY_TABLE,values,"_id = ?",new String[]{String.valueOf(my_id)});
and the Other problem is the returned value. I think in above example I give
id = 1
for 1 row effected. but I want to know that: Is there any way to retrieve the value of updated column(in my example I want to give "15"). Some thing like in SQL server that we fetch from
"##ROWCOUNT" or "##fetch_status"
Hope to describe it well. thanks.
Android's update() function can set only fixed values.
To execute your SQL statement, you have to use execSQL():
db.execSQL("Update my_table set _score = _score + 5 where _id = 1");
In SQLite, the UPDATE statement does not return any data (except the count of affected rows). To get the old or new data, you have to execute a SELECT separately.
For your first problem about updating the score value try this:
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(my_table, values, _id + " = ?",
new String[] { String.valueOf(my_id) });
}

SQLiteDatabase, Updated Values not matching in select query

I got stuck in a very strange issue. Where i am able to update the db Values when when trying to fetching the rows corresponding to that values i am not getting anything.
In this database, i inserted these rows, the date were 29, june for the last two rows, but when i updated these dates to 15, and tried to fetch the rows corresponding to that date
String where = COL_DATE + " = ?";
String[] args = {"15"};
Cursor cursor = db.query(TABLE_DAILY_EXPENSE, null, where, args, null, null, null);
Then Log.d(TAG, "Cursor count= " + cursor.getCount());gives 0`
Where as by fetching through month, it gives count = 2.
So i concluded, that somewhere after updating the fields, its not matching that updated field for fetching that corresponding row. But why this is happening?? No Idea.
`
The value in the database is a number.
The value you are searching for is a string, which is different.
The Android database API allows only strings as parameters in most places, so you have to insert the number directly into the SQL command:
String where = COL_DATE + " = " + 15;
String[] args = null;

Android select from SQLite database where date (stored as int) = today?

I have dates stored in a SQLite table in int format (i.e. milliseconds - derived from System.currentTimeMillis()). I now want to query all rows from the table where the date is equal to today's date, but the query below always returns zero, even though file_uploaded_date in the upload_history table is set to today's date in at least 20 rows.
Can anyone tell me what's wrong with my query?
String today = new SimpleDateFormat("d-MMMM-yyyy").format(new Date());
String sql = "SELECT COUNT(*) as uploaded_today from upload_history "
+ "WHERE strftime('%-d-%b-%Y',file_uploaded_date) = strftime('%-d-%b-%Y','" + today + "')";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()){
int uploadedToday = cursor.getInt(cursor.getColumnIndex("uploaded_today"));
}
I'd say you have your format-strings incorrect.
I don't see a %b argument in the documentation. For month, you would want to use %m. Also %-d doesn't seem right. Use the following format string instead: %Y%m%d.
Further, you are then passing a poorly-formatted string into the query, rather than the int, and relying an sqlite to correct that. Instead, compare to a SimpleDateFormat( "yyyyMMdd" ) without further conversion.
Your code would then look like this:
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
String sql = "SELECT COUNT(*) from upload_history "
+ "WHERE strftime('%Y%m%d',file_uploaded_date) = '" + today + "')";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()){
int uploadedToday = cursor.getInt(0);
}
(Note that if you return only one column, you don't have to name it, and can just access the first column for the result.)
Further, please be aware that this query will cause a table-scan every time it's executed, as sqlite needs to convert all the epochs to strings. You'd be better off adding a date column to the table, and update it once:
UPDATE upload_history
SET just_the_date = strftime('%Y%m%d',file_uploaded_date)
This will then allow you to do much quicker searches, and even search by year or month, using the LIKE operator. If your table is very large, you might want to put an index on that column as well.
You can add date in db as a string in date format like yyyy-mm-dd hh-mm-ss and compare the same while retrieving it from database using sql query.

Android. sqlite update last inserte row

I want to update the last inserted row, but I get an error:
08-20 12:08:23.091: E/AndroidRuntime(13598): android.database.sqlite.SQLiteException: near "ORDER": syntax error
(code 1): , while compiling: UPDATE REVIEW SET json=? WHERE ORDER BY
date DESC LIMIT 1
My code:
public int updateDataJSON(Review review) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_JSON, review.getJson());
return db.update(TABLE_REVIEW, values, " ORDER BY date DESC LIMIT 1", null);
}
You have to read the last date in a separate step:
db.update(..., "date = (SELECT max(date) FROM ReviewTable)", ...);
(If there are multiple rows with the same date value, this will update all of them.)
ORDER BY and such are only valid in SELECT queries, not UPDATEs.
Consider the following:
Store the last inserted row id as returned by a call to insert():
long lastInsertRowId = db.insert(...);
Use the rowid in the update like
db.update(TABLE_REVIEW, values, "ROWID=?", new String[] { String.valueOf(lastInsertRowId)2 });

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

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
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();
}

Categories

Resources