I have to below table structure of my sqlite database in android
I want to update value to "answer" column according to the ques id.
How do I do it?
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_Answer, answer);
// Inserting Row
db.insert(TABLE_Question, null, values);
db.close(); // Closing database connection
I want to insert value to "answer" column according to the ques id.
This operation called "update" instead of "insert".
insert: means to add new record in table,
update: means change value of any exist row columns
so required operation is update.use update method as:
String where = "Ques_id=?";
String[] whereArgs = new String[] {String.valueOf(Ques_id)};
ContentValues values = new ContentValues();
values.put(KEY_Answer, answer);
db.update(TABLE_Question, values, where, whereArgs);
insert() inserts a new row. To update a column on an existing row, use update() with a selection like "Ques_id=" + id.
Related
I'm using SQlite in my Android app and the task is - how can I update all the rows in one table?
I have a 1st column with name "cl_id" (integer numbers 1-2-3-4..) and after deleting some rows, I wan't to make a cycle to fill this 1st column with a new values to keep them in right order.
I was trying to execute:
data.put("cl_id",index);
db.update("mdb_table_contactList", data, null, null);
but it's updates all the values in the first column :(
To update the field in specific row, try this;
ContentValues data = new ContentValues();
data.put("cl_id",index);
db.update("mdb_table_contactList", data, "id="+_id, null);
db.close();
It's good practice to have a primary key for each row data.
Here _id would be your primary key.
"just give rowId and type of data that is going to be update in ContentValues."
public void updateStatus(String id , int status){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues data = new ContentValues();
data.put("status", status);
db.update(TableName, data, "columnName" + " = "+id , null);
}
Try this it must work
void updateDatail(String id) {
ContentValues data = new ContentValues();
data.put("cl_id",index);
db.update("mdb_table_contactList", data, "id=?", new String[]{id});
db.close();
}
I have the following code to update or insert database, where q_id is my primary key
public long updateResponse(int response, int q_id) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
long id = 0;
contentValues.put(VivzHelper.Q_ID, q_id);
contentValues.put(VivzHelper.QUESTION_RESPONSE, response);
id = db.insertWithOnConflict(VivzHelper.TABLE_QUESTION_TEXT, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
if(id==-1)
Log.d("failed", "failed"+response);
else
Log.d("success","success"+response);
return id;
}
Above code is updating/inserting QUESTION_RESPONSE but making all other column in that row as null in table.. Help
Above code is updating/inserting QUESTION_RESPONSE but making all other column in that row as null in table
That's what the "replace" conflict resolution does. If the insert would result in a conflict, the conflicting rows are first deleted and only then is the new row inserted. NULL is the default default value for a column.
If you need to retain other column data in the row, use an UPDATE query. For example, to update the response column to the row with the specified id:
contentValues.put(VivzHelper.QUESTION_RESPONSE, response);
db.update(VivzHelper.TABLE_QUESTION_TEXT, contentValues,
VivzHelper.Q_ID + "=?", new String[] { String.valueOf(q_id) });
I had created two table in my database, In both table I am inserting value at the same time, now what I want to do is that, I want to insert record in second table, but the condition is that, if there is two same record then I want insert only one record not duplicate value, In second table there is two field one is id and second is category, when user insert two same category that time I want to insert only one entry, below is my code which is not working properly, It insert all record accept duplicate value..
public long InsertCat(String idd, String cat)
{
try
{
SQLiteDatabase db;
long rows = 0;
db = this.getWritableDatabase();
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_CATEGER + " WHERE Category='"+cat+"'",null);
while(c.moveToNext())
{
if(c.getString(0).equals(cat))
{
flag=true;
}
}
if(flag==true)
{
rows=db.update(TABLE_CATEGER, Val, "Category='"+cat+"'" , null);
System.out.print(rows);
db.close();
}
if(flag==false)
{
rows = db.insert(TABLE_CATEGER, null, Val);
System.out.print(rows);
db.close();
}
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
Put all your values inside ContentValues and then call this on writableDatabase
db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
EDIT:
Well all you need is only this part of code
SQLiteDatabase db;
long rows = 0;
db = this.getWritableDatabase();
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
rows = db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
insertWithOnConflict methods follows the last parameter as the reaction algorithm when an duplicate row is Found. And for a duplicate row to be found, the primary keys has to clash. If all this satisfys the row would surely get Replaced :-/ If not something else is going wrong..
While creating your table, put constraint on your column(Primary key or Unique key).This will not only the duplicate value to be inserted into your database.
This is working for me,and i also created Category as a primary key..
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
long rows=db.insertWithOnConflict(TABLE_CATEGER, null, Val,SQLiteDatabase.CONFLICT_REPLACE);
System.out.print(rows);
Log.d("kkkkkkkkkk",""+ rows);
db.close();
return rows; // return rows inserted.
Check with the primary key of which you want assign then while inserting check with on duplicate key..
if you want you update the row
on duplicate key update
As mentioned i am writing the code on duplicate key
INSERT OR REPLACE INTO TABLE_CATEGER(value1,value2,value3)
Use the following query
INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)
It will add new row if it does not exist or update row if it exists.
hope this will help you.
use insertWithOnConflict() method instead of insert()
response = sqLiteDatabase.insertWithOnConflict(TABLE_TRACKER_LOGS_LINES, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
I wont to update a single cell of a row in the database. However the row contains of 5 columns so and i would like to not passing all the other values as well as they should remain the same.
I have this code snippet:
Cursor cursor = db.query(STATION_TABLE, null, null, null, null, null, null);
//If the database already include some stations.
if(cursor.moveToFirst())
{
ContentValues stationValues = new ContentValues();
for(StopLocation station: stations)
{
stationValues.clear();
//The database already includes the station
if(cursor.getString(POS_STA_ID).equals(station.getId()))
{
values.put(KEY_STA_DISTANCE, "null");
db.update(STATION_TABLE, stationValues, KEY_STA_ID + "=?", new String[]{station.getId()});
}
The db.update method throws this exception:
java.lang.IllegalArgumentException: Empty values
Any ideas on how to solve this?
If I understand the question correctly and assuming you are always dealing with one row, there are two possible ways to approach this:
First:
Get the values of all fields in the entire row, and declare them as content values before updating:
ContentValues cv = new ContentValues();
cv.put("Field1","123");
cv.put("Field2","True")
Second:
Use execSQL() method:
String strSQL = "UPDATE your_table SET Field1 = foo WHERE POST_STA_ID = "+ station.getId();
myDataBase.execSQL(strSQL);
I am facing a problem here. I am trying to bulk update my table i.e trying to update multiple rows in the database. The update is simple. I just need to set a column value to 1 which is actually used as a flag in the app. So I want to set the value to 1 and in the where clause I give the string array of all the ids where i want it to set.
But the problem is that it gives me an "android.database.sqlite.SQLiteException: bind or column index out of range:" . However when a single value is provided either as string or an string array, the update works fine.
here is the query
db.update( tableName, cv, Z_ID + "=?", items );
where items is of type String[ ]
kindly tell me what am I missing?
regards
Fahad Ali Shaikh
That is not going to work I believe based on the one line you gave.
If we look at the method call signature :
update(String table, ContentValues values, String whereClause, String[] whereArgs)
so:
ContentValues cv=new ContentValues(); cv.put(colName, new Integer(1));
String[] items = new String []{String.valueOf(Z_ID)}
db.update( tableName, cv, Z_ID + "=?", items );
Does you code look something like this?
Your items array must match up with the where clause. A different example would look something like this:
ContentValues cv=new ContentValues(); cv.put(salesColName, new Integer(4534));
String whereClause = "band=? and album=?"; String whereArgs = new String [] { "U2", "Joshua Tree" };
db.update( tableName, cv, whereClause , whereArgs);