I’m trying to write three different methods for inserting, updating and deleting data in SQLite Database in Android. So far I can insert data in the database, but I can’t understand how to add the where clause in SQL.
Here is the code I’m using :
The update methods:
public boolean updateSQL(String tableName,String key,String value){
return updateData(tableName,key,value);
}
private static boolean updateData(String tableName,String key,String value){
sqliteDb = instance.getWritableDatabase();
String where = "id=?";
ContentValues values = new ContentValues();
values.put(key, value);
values.put(key, value);
sqliteDb.update(tableName, values, where, null);
return true;
}
… and I’m invoking this method like this:
dbHelper.updateSQL("saved_codes", "code_id", "3");
//dbHelper is an instance to a custom DatabaseHelper class.
.. and the delete methods:
public boolean deleteSQL(String tableName,String key,String value){
return deleteData(tableName,key,value);
}
private static boolean deleteData(String tableName,String key,String value) {
sqliteDb = instance.getWritableDatabase();
ContentValues values = new ContentValues();
String where = null;
String[] whereArgs = null;
values.put(key, value);
values.put(key, value);
sqliteDb.delete(tableName, where, whereArgs);
return true;
}
I know that the Strings where and whereArgs are null, but actually I can’t understand how to add them.
I don’t expect someone to write the code for me, but some good advice, suggestions or even samples from the internet are welcome.
You need whereArgs for
something like :
where 42 would be the _id of the row to update. Also prefer BaseColumns._ID to “id”.