Change a value in a column in sqlite - android

I need to update a value in a column from a certain table. I tried this :
public void updateOneColumn(String TABLE_NAME, String Column, String rowId, String ColumnName, String newValue){
String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = "+newValue+" WHERE "+Column+ " = "+rowId;
db.beginTransaction();
SQLiteStatement stmt = db.compileStatement(sql);
try{
stmt.execute();
db.setTransactionSuccessful();
}finally{
db.endTransaction();
}
}
and I call this method like this :
db.updateOneColumn("roadmap", "id_roadmap",id,"sys_roadmap_status_mobile_id", "1");
which means that I want to set the value 1 in the column sys_roadmap_status_mobile_id when id_roadmap = id.
The problem is that nothing happens. Where is my mistake?

Easy solution:
String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = '"+newValue+"' WHERE "+Column+ " = "+rowId;
Better solution:
ContentValues cv = new ContentValues();
cv.put(ColumnName, newValue);
db.update(TABLE_NAME, cv, Column + "= ?", new String[] {rowId});

The below solution works for me for updating single row values:
public long fileHasBeenDownloaded(String fileName)
{
SQLiteDatabase db = this.getWritableDatabase();
long id = 0;
try {
ContentValues cv = new ContentValues();
cv.put(IFD_ISDOWNLOADED, 1);
// The columns for the WHERE clause
String selection = (IFD_FILENAME + " = ?");
// The values for the WHERE clause
String[] selectionArgs = {String.valueOf(InhalerFileDownload.fileName)};
id = db.update(TABLE_INHALER_FILE_DOWNLOAD, cv, selection, selectionArgs);
}
catch (Exception e) {
e.printStackTrace();
}
return id;
}

Related

Update SQLITE query

I need only one table and only one row and update new displacement in it.
For Creating Table
private static void createAllTables(SQLiteDatabase database) {
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " ("
+ TOTAL_DISPLACEMENT_DISTANCE + " TEXT, "
+ USER_ID + " TEXT" + ");");
}
For Updating Table (I remove previous displacement and then insert it new displacement, But i Want to update already existing displacement)
public void insertDisplacement(String id, String displacement) {
try {
deleteDriverLocData();
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
}
For getting displacement
public String getDisplacement() {
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
Cursor cursor = database.query(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
cursor.moveToFirst();
String totaldisplacement = cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE));
return totaldisplacement;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
For deleting displacement
public void deleteDriverLocData() {
try {
database.delete(NewDatabaseForInRideData.IN_RIDE_DATA, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
You have to make object of contentvalue
ContentValues cv = new ContentValues();
cv.put("displacement1","231"); //These Fields should be your String
values of actual column names
cv.put("displacement2","21");
cv.put("displacement3","21");
after this, you can use update query which SQLite provides
database.update(TableName, cv, "USER_ID ="+id, null);
The following or something along the lines of the following could be used as a replacement for the insertDisplacement method :-
public void insertOrUpdateDisplacement(String id, String displacement) {
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
String whereclause = NewDatabaseForInRideData.USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = database.query(NewDatabaseForInRideData.IN_RIDE_DATA,
null,
whereclause,
whereargs,
null,null,null
);
if (csr.getCount() < 1) {
deleteDriverLocData();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} else {
//deleteDriverLocData(); ????? Not sure if required or not.
database.update(NewDatabaseForInRideData.IN_RIDE_DATA,contentValues,whereclause,whereargs);
}
csr.close();
}
This will insert if there is no row (I assume for the user_id) otherwise it will update the displacement column of the existing row.

What is wrong with my SQLite update query

My SQLite update query doesn't work, but returns no error...
public void updateData(String stickerPackTitle, String installed) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_INSTALLED, installed);
db.update(TABLE_NAME, cv, "' " + COL_PACK_NAME + " = " + stickerPackTitle + " '", null);
}
Replace update line with this:
db.update(TABLE_NAME, cv, COL_PACK_NAME + " = '" + stickerPackTitle + "'", null);
Below is the right method to use update query in SQLite. You should keep where clause and your where arguments in different parameters. And yes, don't forgot to close the database connection.
db.update(TABLE_NAME, cv, COL_PACK_NAME + " =?", new String[] stickerPackTitle});
db.close();
Try this type of code :
public void update_PrimaryOffer(PrimaryOffer p)
{
// TODO Auto-generated method stub
ContentValues contentValues = new ContentValues();
contentValues.put("businessId", p.getBusinessId());
contentValues.put("primaryOfferDiscount", p.getPrimaryOfferDiscount());
contentValues.put("offerImage", p.getOfferName());
contentValues.put("businessType", p.getBusinessType());
contentValues.put("businessName", p.getBusinessName());
contentValues.put("businessInformation", p.getBusinessInformation());
contentValues.put("businessImage", p.getBusinessImage());
contentValues.put("offerName", p.getOfferName());
contentValues.put("offerAddress", p.getOfferAddress());
contentValues.put("phoneNumber", p.getPhoneNumber());
contentValues.put("originalPrice", p.getOriginalPrice());
contentValues.put("expiryDate", p.getExpiryDate());
contentValues.put("latitude", p.getLatitude());
contentValues.put("longitude", p.getLongitude());
contentValues.put("likeStatus", p.getLikeStatus());
contentValues.put("favoriteStatus", p.getFavoriteStatus());
contentValues.put("likeCount", p.getLikeCount());
// contentValues.put("DateTime", p.getDateTime());
Cursor cursor = sqLiteDatabase.rawQuery("select * from "+TABLE_RECENT_PRIMARY_OFFER+";", null);
if (cursor.moveToFirst()) {
do {
int ii = sqLiteDatabase.update(TABLE_RECENT_PRIMARY_OFFER, contentValues, "businessId="+ p.getBusinessId(),null);
System.out.println("SQLITE UPDATE SCHEDULER---->" + ii);
}while(cursor.moveToNext());
}
cursor.close();
}

Android sqlite update row by calling method

I'm trying to update a row in my sqlite database but i cant find out what is wrong... I'm using this method id my DbAdapter :
public boolean updateRow(long rowId, String TimeDone, String ActDone) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TIME, TimeDone);
newValues.put(KEY_ACT, ActDone);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
And in my Activity i try to update a row by doing this :
String a = "20:34:23";
String item2 = spnr.getSelectedItem().toString();
long rowId = spnr.getSelectedItemId();
ContentValues newValues = new ContentValues();
newValues.put("Time", a);
newValues.put("Activity",item2);
myDb.updateRow(rowId, a, item2);
Am i forgetting something , or i'm doing something wrong ?
Thanks in advance!
EDIT:
I have tried this way;
public boolean updateRow(long rowId, String TimeDone, String ActDone) {
String where = KEY_ROWID + "= ?" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TIME, TimeDone);
newValues.put(KEY_ACT, ActDone);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
But i get the following error :
12-20 17:45:12.521: E/AndroidRuntime(1979): android.database.sqlite.SQLiteException: variable number must be between ?1 and ?999 (code 1): , while compiling: UPDATE MainTable SET Activity=?,Time=? WHERE _id= ?0
And if i do this way :
public boolean updateRow(long rowId, String TimeDone, String ActDone) {
ContentValues newValues = new ContentValues();
newValues.put(KEY_TIME, TimeDone);
newValues.put(KEY_ACT, ActDone);
return db.update(DATABASE_TABLE,newValues, KEY_ROWID + " = ?",
new String[] { String.valueOf(rowId) })!= 0;
}
I get no errors but the row dosent update .
This line is not giving you the correct ID:
long rowId = spnr.getSelectedItemId();
Instead, call getSelectedItem() and get your ID from the object.
Did you forget to put ? in String where = KEY_ROWID + "=" + rowId;
Then change it to String where = KEY_ROWID + "= ?" + rowId;
or try something like this:
public int updateRow(long rowId, String TimeDone, String ActDone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(KEY_TIME, TimeDone);
newValues.put(KEY_ACT, ActDone);
return db.update(DATABASE_TABLE,newValues, KEY_ROWID + " = ?",
new String[] { String.valueOf(rowID) });
}
Hope it may help.

SQLite database update query with multiple where conditions in Android

I want to update my database table with multiple where conditions. I already did with single where condition
db.update(TABLE_MISSING_ITEMS, values, KEY_AUTHOR + " = ?",
new String[] { String.valueOf(items.getAuthor()) });
Now i want 2 where condition.
P.S :- No raw query
You can separate the different WHERE conditions with ANDlike this:
db.update(TABLE_NAME,
contentValues,
NAME + " = ? AND " + LASTNAME + " = ?",
new String[]{"Manas", "Bajaj"});
The way I solved my need
public boolean checkHususiKayit(String baslik, String tarih) {
boolean varMi = false;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_BASLIK,
DBHelper.COLUMN_H_TARIH,
DBHelper.COLUMN_H_YOK_TUR,
DBHelper.COLUMN_H_AD,
DBHelper.COLUMN_H_WEB_ID,
DBHelper.COLUMN_H_NUMARA,
DBHelper.COLUMN_H_YURD_ID,
DBHelper.COLUMN_H_YETKILI_AD,
DBHelper.COLUMN_H_YETKILI_ID,
DBHelper.COLUMN_H_TEL,
DBHelper.COLUMN_H_EMAIL,
DBHelper.COLUMN_H_ADDRESS,
DBHelper.COLUMN_H_VAR,
DBHelper.COLUMN_H_GOREVLI,
DBHelper.COLUMN_H_YOK,
DBHelper.COLUMN_H_IZINLI,
DBHelper.COLUMN_H_HATIMDE};
String whereClause = DBHelper.COLUMN_H_BASLIK + " = ? AND " + DBHelper.COLUMN_H_TARIH + " = ?"; // HERE ARE OUR CONDITONS STARTS
String[] whereArgs = {baslik, tarih};
Cursor cursor = database.query(DBHelper.TABLE_NAME_HUSUSI, kolonlar, whereClause, whereArgs, null, null, null + " ASC");
while (cursor.moveToNext()) {
varMi = true;
}
database.close();
cursor.close();
return varMi;
}
THIS CAN ALSO BE DONE LIKE THIS
public void UpdateData(int Cid,int flag,String username,String password)
{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Status",flag);//I am updating flag here
database.update(TABLE_NAME, cv, ""+KEY_UserName+"= '"+ username+"' AND "+KEY_CID+"='"+Cid+"' AND "+KEY_Password+"='"+password+"'" , null);
database.close();
}
Try this simple query
db.update(TABLE_FF_CHECKLIST_DATA,contentValues, "FFCHECKLISTID = ? and TASK_ID_CHK = ?" , new String[] {"EHS" , "CTO914"});
where "EHS" is value in column FFCHECKLISTID and CTO914 is value in TASK_ID_CHK.

Android db.update SQLite

I have a small problem with the method db.update. I need to change a string that corresponds to that received by the query. For example from the query I get the string "hello", if the change in "hello1" must change all the strings "hello".
In my Cursor I have name_s = c.getString(3);
And this is my update:
cv.put(Table1.ABC, Ecia.getText().toString());
db.update(Table1.TABLE_NAME, cv, Table1.ABC+ " = ?", new String[] { name_s});
try this :
String newval=Ecia.getText().toString();
String name_s = c.getString(3);
setMyField(name_s , newval);
public int setMyField(String currvalue , String newvalue) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Table1.ABC, newvalue);
// updating row
return db.update(Table1.TABLE_NAME, values, Table1.ABC + " = ?",
new String[] { currvalue });
}

Categories

Resources