Android SQLite, update specific field from specific row - java

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.

Related

Android Java SQLite not updating?

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.

How to use prepared statement for sql?

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

Filter and edit DB row Android studio

I have making project with DB and I have layout with two edittexts in that edittext on activity start I load one column from my DB and display it and in other edittext is text with I want to find specific row in DB table.
When I find that row I need to edit some values in this row. Here is my updatecode in DBadapter.java
// Change an existing row to be equal to new data.
public boolean updateRow(long containercode_row, String lkwnummer,String uniqueid, String containerbarcode,
String timein, String timeout, String howout, String latitudein,
String longitudein, String latitudeout, String longitudeout, String status) {
String where = KEY_CONTAINERBARCODE + "=" + containercode_row;
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_LKWNUMMER, lkwnummer);
newValues.put(KEY_UNIQUEID, uniqueid);
newValues.put(KEY_CONTAINERBARCODE, containerbarcode);
newValues.put(KEY_TIMEIN, timein);
newValues.put(KEY_TIMEOUT, timeout);
newValues.put(KEY_HOWOUT, howout);
newValues.put(KEY_LATITUDEIN, latitudein);
newValues.put(KEY_LONGITUDEIN, longitudein);
newValues.put(KEY_LATITUDEOUT, latitudeout);
newValues.put(KEY_LONGITUDEOUT, longitudeout);
newValues.put(KEY_STATUS, status);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
I need to find row throught KEY_CONTAINERCODE value but I don't know how to make this code in activity where I want to find that row and edit it?
you can update your values by making a method in CommonUtill file like this:
public int updateRecords(String table, ContentValues values,
String whereClause, String[] whereArgs) {
int a = db.update(table, values, whereClause, whereArgs);
return a;
}
there is no need for creating a separate method for this for good practices.

Update integer values in SQLite database (java)

I am pretty new to SQLite databases, so please forgive me...
I have a database with integer values. When updating a row in the database using the code below, there is somehting I don't understand. whereArgs is of type String[], though the values you are looking for are integers, so I would expect that one should pass in a int[].
SQ.update(table, values, whereClause, whereArgs)
Where do I go wrong?
Example code (hypothetical):
public void changeOneIntoTwo(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getWritableDatabase();
String selection = "ValuesColumn = ?";
String[] args = {"1"};
ContentValues cv = new ContentValues();
cv.put("ValuesColumn", 2);
SQ.update("MyTable", cv, selection, args);
}
selection is the condition that you put in where clause of Sql query and args is what replaced by "?" of selection .
for example : lets assume you need your sql query select * from Mytable where ValuesColumn ='1' and Name = 'MVB'. so in this case
String selection = "ValuesColumn = ? AND Name = ?";
String[] args = {"1","MVB"};

Update multiple rows in Android sqlite

I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:
METHODS FOR ANDROID SQLITE DATABASE QUERY:
public void updateUser(String newProfession, String newCountry, String sx, String ag) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
Cursor cursor = db.rawQuery(query, null);
cursor.close();
db.close();
}
public int countAll() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
db.close();
return cnt;
}
CALLING THE METHODS
public void updateUsersClicked(View view) {
int allData = db.countAll();
for (int i = 0; i < allData; i++) {
db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
System.out.println("T H I S I S T H E R E S U L T: " + i);
}
}
Use execSQL() and not rawQuery() for updates.
rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.
Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.
You don't need to do the for loop
a single QSL "Update" query is enough if you want to update All the female with age 30.
If you are new to SQL you can view a simple example here:
Simple SQL Update example
If you want to do something else - please edit your question

Categories