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);
Related
I am using following statement to update a row in the Content provider's table.
ContentValues values = new ContentValues();
values.put(ReminderData.REMINDERS_STATUS, Boolean.valueOf(isChecked));
mCtx.getContentResolver().update(ReminderData.CONTENT_URI, values, ReminderData._ID + "=?", new String[]{cursor.getString(cursor.getColumnIndex(ReminderData._ID))});
Values:
ReminderData.CONTENT_URI : content://com.android.firstapp.data/reminder
cursor.getString(cursor.getColumnIndex(ReminderData._ID)) : 2
I always get the result as 0, i.e. 0 rows updated. But I have a row in the table with id 2.
Also when I try to retrieve a row from the content provider using below code:
Cursor cursor = getContentResolver().query(ReminderData.CONTENT_URI, null, ReminderData._ID+"=?", new String[] {id+""}, null);\
id value is 3.
But I get all the rows in the cursor with cursor count as 5.
I don't know what is the issue. Please help. TIA.
I've a situation in sqlite that make you an example: My table has two fields,"_id" and "_score" . I have a record with _id=1, _score=10. I want to update this row to 5 number more than the current value(10). in SQL i can do it simple like:
Update my_table set _score = _score + 5 where _id = 1
but in sqlite I have these that I don't know how can fix it to what I want :
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(MY_TABLE,values,"_id = ?",new String[]{String.valueOf(my_id)});
and the Other problem is the returned value. I think in above example I give
id = 1
for 1 row effected. but I want to know that: Is there any way to retrieve the value of updated column(in my example I want to give "15"). Some thing like in SQL server that we fetch from
"##ROWCOUNT" or "##fetch_status"
Hope to describe it well. thanks.
Android's update() function can set only fixed values.
To execute your SQL statement, you have to use execSQL():
db.execSQL("Update my_table set _score = _score + 5 where _id = 1");
In SQLite, the UPDATE statement does not return any data (except the count of affected rows). To get the old or new data, you have to execute a SELECT separately.
For your first problem about updating the score value try this:
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(my_table, values, _id + " = ?",
new String[] { String.valueOf(my_id) });
}
How should i get most recent added record from database, where COL_2 should == param that I pass into it.
I can get all records where COL_2 is equal to param with this code, but I need only recent one
public Cursor getRowsLast(String param) {
SQLiteDatabase db = helper.getWritableDatabase();
String[] COLS = new String[]{DatabaseHelper.COL_1,DatabaseHelper.COL_2, DatabaseHelper.COL_3,DatabaseHelper.COL_4};
String where = param;
Cursor c = db.query(true, DatabaseHelper.TABLE_NAME, COLS, DatabaseHelper.COL_2 + " = '" + where + "'", null, null, null, null, null);
if(c != null){
c.moveToFirst();
}
return c;
}
The most reliable way to get the most recent row in a table is to have a column defined in the table for the time of insert/update. Make sure this value is accurate at the time of insert/update, and create an index on it. You can then sort (descending) on this column to determine which one is the most recent - it will be the first row.
As the automatically generated ID values increase with every insert, the row with the highest ID will be the one that was inserted most recently. So add an 'order by _id desc' and the first row will be the most recently inserted one.
Note - this does not cover updates. If you need the row most recently inserted or updated, you'll have to use an additional timestamp column like Doug Stevenson suggested.
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 have created a working SQlite database in my application. I can add new values to the database. I have even created a method which displays all the results of the table on a new activity.
What I would this new activity really to do, is to display the most recent entry into text views. Picking individual fields and slotting them into correct text views. How do I go about doing this?
Assuming you are using autogenerated ID in your table, you need to sort the results based on ID and limit the results to '1' which will return only that row.
return db.query(true, "yourTableName", new String[] { "columnNamesYouwanttoQuery" },
null, null, null, null, "_id DESC", "1");
Then loop through the cursor and get yourColumns
Cursor cur = adaptor.getMileageReport(AutoMainActivity.CARNAME);
startManagingCursor(cur);
if (cur.moveToFirst()) {
do {
String retrievedVal = cur.getString(0);
}
}