Android sqlite update row by calling method - android

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.

Related

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

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.

Selecting NULL values in Android SQLite

I'm executing the following method with no success beacause of the selectArgs being incorrect (at least this is what I believe.
findAll:
public Collection<Object> findAllByCodigoSetorOrderByStatusWhereDataAgendamentoIsNull(Integer vendedor) {
Collection<Object> objects = null;
String selection = Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " AND " + Object.FIELDS[6] + "=?";
String[] selectionArgs = new String[] { "''", "'null'", "NULL", String.valueOf(vendedor) };
Collection<ContentValues> results = findAllObjects(Object.TABLE_NAME, selection, selectionArgs, Object.FIELDS, null, null, Object.FIELDS[4]);
objects = new ArrayList<Object>();
for (ContentValues result : results) {
objects.add(new Object(result));
}
return objects;
}
findAllObjects:
protected Collection<ContentValues> findAllObjects(String table, String selection, String[] selectionArgs, String[] columns, String groupBy, String having, String orderBy) {
Cursor cursor = null;
ContentValues contentValue = null;
Collection<ContentValues> contentValues = null;
try {
db = openRead(this.helper);
if (db != null) {
cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
contentValues = new ArrayList<ContentValues>();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
contentValue = new ContentValues();
for (int c = 0; c < cursor.getColumnCount(); c++) {
contentValue.put(cursor.getColumnName(c), cursor.getString(c));
}
contentValues.add(contentValue);
cursor.moveToNext();
}
}
return contentValues;
} finally {
close(db);
}
}
How can I correctly select and compare a column to - null, 'null' and '' using the db.query?
Android's database API does not allow to pass NULL values as parameters; it allows only strings.
(This is a horrible design bug. Even worse, SQLiteStatement does allow all types for parameters, but works only for queries that return a single value.)
You have no choice but to change the query string to blah IS NULL.
Old question but i was still stuck on this for a few hours until i found this answer. For whatever reason this strange behaviour (or bug) still exists within the android sdk, if you want to query against null values simply do
SQLiteDatabase db = getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("columnName", newValue);
String nullSelection = "columnName" + " IS NULL";
db.update("tableName", contentValues, nullSelection, null);
db.close();
In this example i am updating values, but it is a similar concept when just selecting values
As mentioned in other answers, for null "IS NULL" need to be used. Here is some convenience code for having both null and strings (I'm using delete in the example but the same can be done for other methods, e.g. query):
public void deleteSomething(String param1, String param2, String param3) {
ArrayList<String> queryParams = new ArrayList<>();
mDb.delete(TABLE_NAME,
COLUMN_A + getNullSafeComparison(param1, queryParams) + "AND " +
COLUMN_B + getNullSafeComparison(param2, queryParams) + "AND " +
COLUMN_C + getNullSafeComparison(param3, queryParams),
queryParams.toArray(new String[0]));
}
private String getNullSafeComparison(String param, List<String> queryParams) {
if (param == null) {
return " IS NULL ";
} else {
queryParams.add(param);
return " = ? ";
}
}
You can bind NULL values to SQLiteStatement:
SQLiteDatabase db = getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("UPDATE table SET " +
"parameter=? WHERE id=?");
if (param == null)
stmt.bindNull(1);
else
stmt.bindString(1, param);
stmt.execute();
stmt.close();
db.close();

Change a value in a column in sqlite

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

How to update data in Sqlite?

In my android application I am using sqlite database. I use the following code to update data but the data is not updated.
public int setCurrentLevel(int level)
{
//update table level set currentlevel = level;
int slevel = level;
Log.d("QUIZ APP", "inside on setcreatelevel is "+slevel);
ContentValues args = new ContentValues();
args.put("currentlevel", slevel);
return db.update("level", args, "currentlevel" + ">=" + slevel, null);
}
Here you go
db.update("level",args,"currentlevel>= ?", new String[] { String.valueOf(level) });
Use this kind of code inside your function
public boolean updateTitle(long rowId, String isbn,
String title, String publisher)
{
ContentValues args = new ContentValues();
args.put(KEY_ISBN, isbn);
args.put(KEY_TITLE, title);
args.put(KEY_PUBLISHER, publisher);
return db.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
Try This
public int setCurrentLevel(int level)
{
//update table level set currentlevel = level;
int slevel = level;
Log.d("QUIZ APP", "inside on setcreatelevel is "+slevel);
ContentValues args = new ContentValues();
args.put("currentlevel", slevel);
return db.update("level", args,
"currentlevel" + ">=" + slevel, null)>0;
}
use this query......... also mention some condition on which you want to fire this update
db.execSQL("UPDATE "+tableName+" SET "+columnNameValue+" WHERE "+condition+"");
your query will look something like:
db.execSQL("UPDATE level SET currentlevel="+slevel +" WHERE currentlevel \\>=" + slevel+"");
Try this,
ContentValues cv = new ContentValues();
cv.put("Field", value);
db.update("Table", cv, "Field='value'", null);

Categories

Resources