I am going nuts over here. I have been trying to update one column in one row inside of my SQLite Database but its just not happening regardless of what I try.The value is never updated and there are no exceptions in my log.
The below code might summarise my problem best.
the updateLatestMessage() function is part of a Database Controller Class.
public void updateLatestMessage(int messageID, int chatID){
Log.d("DB", "message ID =" + messageID); //example output = 125
Log.d("DB", "chat ID =" + chatID); //example output = 2
SQLiteDatabase db = this.getWritableDatabase();
try {
ContentValues cv = new ContentValues();
cv.put("latest_message_id", messageID);
db.update("chat", cv, "chat_id = ?" + chatID, null);
db.close();
//db.update(tableChat.TABLE_NAME, cv, tableChat.getChatId() + " = ?", new String[]{String.valueOf(chatID)}); // tried this before didn't work either
}
catch(Exception e) {
Log.d("DB", "Error: "+e.toString());
}
}
currently latest message has the ID of 5
myDB.chat.updateLatestMessage((int) messageID, globalChatID);//calling the above DB update code
after running this code the latest message still has the id of 5 instead of 125
I am expecting the messageID to be updated inside of the the latest_message_id column inside my already existing chat row.
If the name of the table is "chat", the name of the column in the WHERE clause is "chat_id" and the argument of WHERE clause is chatID, then the recommended way for the update is this:
int result = db.update("chat", cv, "chat_id = ?", new String[]{String.ValueOf(chatID)});
Check the value of result after the statement.
If its value is greater than 0 then the update was successful.
Related
I'm trying to have an SQLite database in android but I have a problem with that:
I'm trying to update the text value in the "response" column with id 0. The first problem I had was that the string I was using for the update used an apostrophe (') and it had syntax errors because sql closes the string with an '. So I now am using a prepared sql statement for that. The problem now is that the long that is returning gives a -1, so that means that no rows were effected. So how can I update my current string to the row with id=0?
Note: the first string also has an ' but was added using the addData funtion and it didn't give any errors just using db.insert, is that the problem, should I replace all my code with prepared statements?
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public long updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE json_response SET response=? WHERE ID='0'";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, newName); // matches second '?' in sql string
long rowId = statement.executeInsert();
return rowId;
}
I have not used prepared statements much so I can't say why that is not working, but why not use the db.update() method? It takes ContentValues as an argument similar to tour addData() method. Give this a shot.
public int updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("json_response",newName);
int rows = db.update(TABLE_NAME, cv, "ID=0", null);
return rows;
}
[EDIT] update() returns an integer representing the number of rows affected instead of which row was affected. Keep that in mind as your variable name rowId implies that is not what you are looking for.
[EDIT 2] And no, there is no problem with the addData() method that I can see. The apostrophe that was added did not cause an error because ContentValues parameterizes the string values before adding them into the database. Basically, all SQL-like syntax will be ignored when inserting values, which is great for security reasons.
The problem is, I think, that WHERE ID='0' will always fail; what you want is WHERE ID=0
I have db table as follows
I want to update status column to 1 with id = 1,2,3.
For a single row I can update with content values
public void updateJobStatus(int callId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues data = new ContentValues();
data.put(AppDBConstants.KEY_JOB_DETAIL_STATUS, 1);
db.update(AppDBConstants.TABLE_JOB_DETAIL, data, AppDBConstants.KEY_JOB_DETAIL_CALL_ID + "=" + callId, null);
db.close();
}
What to do for multiple rows?
Update Your query like this
db.update(AppDBConstants.TABLE_JOB_DETAIL, data, AppDBConstants.KEY_JOB_DETAIL_CALL_ID + " IN (?,?,?)", new String[]{"1","2","3"});
I think you current code is working for multiple id but need some of changes as below to achieve your requirement :
public void updateJobStatus(int[] callIds) {
SQLiteDatabase db = this.getWritableDatabase();
if (db != null) {
db.beginTransaction();
try {
for(int id : callIds){
ContentValues data = new ContentValues();
data.put(AppDBConstants.KEY_JOB_DETAIL_STATUS, 1);
db.update(AppDBConstants.TABLE_JOB_DETAIL, data, AppDBConstants.KEY_JOB_DETAIL_CALL_ID + "=" + id, null);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.close();
}
}
Note : As above you need to pass id array it might be one or multiple.
When you have unknown number of arguments, try this one
String args = TextUtils.join(", ", arrayOfIds);
db.execSQL(String.format("UPDATE %s SET %s = true WHERE %s IN (%s);",
TABLE_INCOMING_MESSAGES, KEY_MESSAGE_SENT, KEY_ID, args));
I am trying to update a specific column in my record within SQLite - the object has various attributes, but I just want to update a single field within that row. Here are my codes:
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(EMAIL, email);
args.put(IS_FAV, isFavorite);
int i = db.update(TABLE_FAVORITES, args, EMAIL + "=" + email, null);
return i > 0;
}
I am using the email for my where clause, i.e update record from favorites, set isFavorite to (given value) where email is (passed in value).
There is a problem with my query, which was caught by logcat, as shown below
android.database.sqlite.SQLiteException: near "#sjisis": syntax error (code 1): , while compiling: UPDATE Favorites SET email=?,isFavorite=? WHERE email=sjkshs#sjisis.com
Can anyone help me identify what is wrong with my codes to produce this error?
P.S my FavoriteObject class has other attributes other than just email and isFavorite, but in this case I am not trying to update them at all
Try to make email in where clause be argument too, i try to change your code but didn't test yet :
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(EMAIL, email);
values.put(IS_FAV, isFavorite);
//add arguments for where clause
String[] args = new String[]{email};
int i = db.update(TABLE_FAVORITES, values, "EMAIL=?", args);
return i > 0;
}
Looks like it's complaining about the email address, perhaps the #.
try
int i = db.update(TABLE_FAVORITES, args, EMAIL + "= ' " + email + "'", null);
ie. single quotes around the email address.
I am trying to update the field of an entry in an SQLiteDatabase using the db.update(...) method, but it seems the value is not stored. I've tried the convenience db.query(...) method right after the update method has been executed and found that the entry is still stored as before the update.
Is there some sort of background work that I must wait for before the query, or where am I going wrong? I am using a singleton extended SQLiteOpenHelper (dbHelper) as recommended in SQLite DB accessed from multiple threads and I've even tried getting a new readable instance of the db from the helper for the query in a new thread, as in the code below:
ContentValues deviceListEntry = new ContentValues();
deviceListEntry.put(DeviceListDBEntry.NODE_ID, nodeID);
...
...
String WHERE = DeviceListDBEntry.NODE_ID + " = ?";
final String[] WHERE_ARG = {String.valueOf(nodeID)};
SQLiteDatabase db = dbHelper.getWritableDatabase();
int listings = 0;
try {
//Update the device in the database DeviceList table
listings = db.update(
DeviceListDBEntry.TABLE_NAME,
deviceListEntry,
WHERE,
WHERE_ARG
);
} catch (Exception e) {
throw new ApiHandlerException("db.update(DeviceList, node " + nodeID + ")", e);
}
Log.e("updateDBdevice", " node " + device.getNodeID() + " listening = " + device.isListening());
final String[] TABLE_COLUMNS = {
DeviceListDBEntry.DEVICE_TYPE,
DeviceListDBEntry.INTERVIEWED,
DeviceListDBEntry.DEVICE_JSON
};
final String where = WHERE;
new Thread(new Runnable() {
#Override
public void run() {
SQLiteDatabase db2 = dbHelper.getReadableDatabase();
Cursor deviceEntry = db2.query(
DeviceListDBEntry.TABLE_NAME, //FROM DeviceList Table
TABLE_COLUMNS, //SELECT * columns
where, //WHERE nodeID =
WHERE_ARG, //args nodeID
null,
null,
null
);
if (!deviceEntry.moveToFirst()) throw new ApiHandlerException("DeviceListDB no entry found - WHERE nodeID = " + nodeID);
if (deviceEntry.getCount() > 1) throw new ApiHandlerException("DeviceListDB duplicate entries - WHERE nodeID = " + nodeID);
String deviceJson = deviceEntry.getString(deviceEntry.getColumnIndexOrThrow(DeviceListDBEntry.DEVICE_JSON));
Log.e("updateDBdevice retreive", " node " + nodeID + " JSON : " + deviceJson);
}
}).start();
I am using a Gson object to parse my device class to a JSON object which is stored in the DB. I know that this works when using the db.insert(...) method.
The query here is only there to see if the update was successful, because I found that explicit queries using other delayed threads (synchronised using a object lock and the same SQLiteOpenHelper) returned values that were not updated.
Is there an obvious thing I am missing or should I consider going to raw SQL commands on the db?
My mistake, I found that I had actually not added the updated JSON object to the new entry. Subsequently the deviceJson column of the listing did not update, but a db.update() was executed...
If "WHERE" clause has "text" column comparison then use single quotes around value. In your case try below line (notice single quotes around ?)
String WHERE = DeviceListDBEntry.NODE_ID + " = '?'";
I want to change a single column inside a row. I'm trying to update the value inside "remindOnDate" field to "reminder" in the "tasks" table.
I tried a few things but they all work only when remindOnDate is null. Once it has a value stored in it, update won't work on it. I don't know why. What am I doing wrong? If the statement is wrong then it shouldn't work even when remindOnDate is null.
I tried this:
ContentValues editTask = new ContentValues();
editTask.put("remindOnDate", reminder);
database.update("tasks", editTask, "_id = ?", new String[]{id+""});
I also tried the following instead of the last line:
database.update("tasks", editTask, "_id = " + id, null);
Here is another thing I tried:
String createQuery = "UPDATE tasks SET remindOnDate = '" + reminder + "' WHERE _id = " + id + ";";
database.execSQL(createQuery);