Is there a way to change android sqlite data? - android

I want to swap sqlite data
now, I am changing data after saving it in a variable
Is there a better way? Thank you
updateDbDate(fromItem.getTitle(),fromItem.getCable(),fromItem.getImg(),toItem.getId());
updateDbDate(toItem.getTitle(),toItem.getCable(), toItem.getImg(),fromItem.getId());
public void updateDbDate(String mTitle, String mCable, String mImg, int id)
{
ContentValues values = new ContentValues();
values.put("title", mTitle);
values.put("cable", mCable);
values.put("bimg", mImg);
db.update(Define.DB, values,"_id = " + "'" + id + "'",null);
}

What I understand is that you want to swap the values of 3 columns between 2 rows for which you know the ids.
If you also know the values of the other 3 columns then your method is correct.
If you don't know them and you have to read them from the table then I think it would be better to just swap the ids:
public void swapIds(int id1, int id2) {
ContentValues values = new ContentValues();
values.put("_id", -1);
db.update(Define.DB, values, "_id = ?", new String[] {String.valueOf(id1)});
values.put("_id", id1);
db.update(Define.DB, values, "_id = ?", new String[] {String.valueOf(id2)});
values.put("_id", id2);
db.update(Define.DB, values, "_id = ?", new String[] {"-1"});
db.close();
}
The 1st update sets temporarily -1 to the first _id, because I guess it is the PRIMARY KEY and it can't be set to id2 because it already exists.
The 2nd update sets id1 to the second _id (it can be done since id1 does not exist in the table from the previous update).
And the 3d update sets id2 to the first _id.
Now you can call the method:
swapIds(100, 200);
Note: this method is not recommended if there are references in other tables to the _id of this table.

Related

Android - SQLite Update Statement

I am playing with an example of SQLite I found on the internet. I have an update statement like this:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?" +
contact.getID(), null);
}
And an update statement like this:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[]{String.valueOf(contact.getID())});
}
Can someone tell me the difference?
Here is the method signature for an update operation on SQLite database.
int android.database.sqlite.SQLiteDatabase.update(
String table, ContentValues values, String whereClause, String[] whereArgs)
From developer.android.com
You may include ?s in the where clause, which will be replaced
by the values from whereArgs. The values will be bound as Strings.
Btw your first example wouldn't work cause you have included
"KEY_ID + " = ?" + contact.getID()" in whereClause param and kept the whereArgs null. The ?s would'nt be replaced by your arg contact.getId()
Change whereClause in 1st example to this: KEY_ID + " = " + contact.getID()
On your 1st example.The code can't update anything.
The update method whereCause params will be convert to some SQL on where case ,It will replace the ? placeholder with whereArgs.
Such as:
In your 1st example.If contact.getId() return 1,The final SQL is like:
update contact set KEY_NAME = 'your contact name ' where KEY_ID = ? 1
but 2st example final SQL is like:
update contact set KEY_NAME = 'your contact name ' where KEY_ID = 1
So,the first example is not work.

Updating rows in Android SQlite

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

How to update the table values

I have the table(shown in fig). I want to update the time column. I have the medicine_id(second column) how to update the different times depend upon the same medicine_id(second column).
Also, I have four rows in my DB when I updated time it should be two row means, I want to remove the other two rows with the particular medicine_id..
I have the following code for update:
if(mon) {
for (int i = 0; i < dosage_per_day; i++) {
mMedicineDbHelper.updateMedicines(new
MedicineTime(row_id, time_InMillies[i]));
}
}
My DB code:
public void updateMedicines(MedicineTime medicineTime) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, medicineTime.getId());
values.put(MEDICINEID, medicineTime.getMedicine_id());
values.put(TIME, medicineTime.getTime_in_millis());
db.update(TABLENAME, values, MEDICINEID + " = ?",
new String[]{String.valueOf(medicineTime.getMedicine_id())});
db.close();
}
It shows exception..
anybody help to solve this...
For the original question asked you're executing the following code:
db.update(TABLENAME, values, MEDICINEID + " = ?",
new String[]{String.valueOf(medicineTime.getMedicine_id())});
For some reason on Android, converting numeric values to Strings and using them for selection args never works properly. See: Android Sqlite selection args[] with int values. The best way to do this is the following:
db.update(TABLENAME, values, MEDICINEID + " = " + medicineTime.getMedicine_id(), null);

Update row in SQlite database by row position in android

I have database which contains "date" column and "item" column.
I want that user could update specific row in the database.
I trying to do it with update method in SQLiteDatabase class.
My problem is that i dont know how to make update method find exactly the row i want.
I saw some example that use it with parameters from one word.
like this:
ourDatabase.update(tableName, cvUpdate, rowId + "=" + item , null);
My problem is that i want to update the row that have specific item and date. so the name of the item alone is not enough.
I tried this code below but its didnt work, hope youll can help me.
public void updateEntry(String item, String date) throws SQLException{
String[] columns = new String[]{myItem, myDate};
Cursor c = ourDatabase.query(tableName, columns, null, null, null, null, null);
long position;
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(date, myDate);
cvUpdate.put(item, myExercise);
int itemAll = c.getColumnIndex(myItem);
int dateAll = c.getColumnIndex(myDate);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if (c.getString(itemAll).equals(myItem) && c.getString(dateAll).equals(myDate))
{
position = c.getPosition();
break;
}
}
ourDatabase.update(tableName, cvUpdate, rowId + "=" + position , null);
}
First, the columns String[] is supposed to contain column names, such as "_ID", or whatever are the column names you have used. Given that you compare the content of the column myItem with the object myItem, I assume there is a confusion somewhere here.
Secondly, rowId and position are different things in SQL, especially if you delete rows, as the row id usually is autoincrement, and especially since your query is not explicitely sorted. Replacing c.getPosition() by c.getLong(c.getColumnIndex(ID_COLUMN)) would make more sense.
Thirdly, sql is nice because you can query it. For example, rather than get all items and loop to find the matching date and item, you can :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
Cursor c = ourDatabase.query(tableName, columns, whereClause, whereArgs, null, null, null);
instead of your for loop.
Forthly, you can even make the query in the update :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
ourDatabase.update(tableName, cvUpdate, whereClause, whereArgs);
Extra tip: use full caps variable names for contants such as column names, it help with readability.

Insert or update in SQlite and Android using the database.query();

is there a way to change my function:
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
this is a raw insert, i would like to change this function to make it update or insert accordingly. i would like to change this becouse i'm already using this function in some places, but now i need to choose if insert a row or update (or ignoring the insert) a row with the same COLUMN_NOME. can someone help me doing this?
i mean i would like to insert a new row ONLY if there isn't another with the same name (as usual you know).
You can use insertWithOnConflict() if you want to insert or update, depending in whether the record exists or not:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_VALUE, value);
// this will insert if record is new, update otherwise
db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
you could call int nRowsEffected = database.update(...); if there are no rows effected by the update either the row doesn't exist (or you hosed your update()!) therefore you need to call database.insert(...). of course if nRowsEffected > 0 then you are done.
You can use execSQL and use INSERT OR REPLACE
String[] args = {"1", "newOrOldCategory"}; // where 1 is the category id
getWritableDatabase().execSQL("INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)", args);
First of all you have write function which is check whether id is exists in particular Table like:
/**
* #param table_name
* #param server_id
* #return
*/
public boolean isServerIdExist(String table_name, int server_id) {
long line = DatabaseUtils.longForQuery(mDB, "SELECT COUNT(*) FROM " + table_name + " WHERE id=?",
new String[]{Integer.toString(server_id)});
return line > 0;
}
You have to pass table_name and id in that like
/**
* INSERT in TABLE_ACCOUNT_DEVICE
**/
public long insertOrUpdateAccountDevice(int server_id, int account_id,
String device_name, String device_id,
String last_active, String itp,
String utp, int status) {
ContentValues values = new ContentValues();
values.put(ACCOUNT_DEVICE_ACCOUNT_ID, account_id);
values.put(ACCOUNT_DEVICE_DEVICE_NAME, device_name);
values.put(ACCOUNT_DEVICE_DEVICE_ID, device_id);
values.put(ACCOUNT_DEVICE_LAST_ACTIVE, last_active);
values.put(ACCOUNT_DEVICE_ITP, itp);
values.put(ACCOUNT_DEVICE_UTP, utp);
values.put(ACCOUNT_DEVICE_STATUS, status); // 0=pending, 1=active, 2=Inactive, -1=not_found
/**
* isServerIdExists
*/
if (isServerIdExists(TABLE_ACCOUNT_DEVICE, server_id)) {
values.put(ACCOUNT_DEVICE_SERVER_ID, server_id);
return mDB.insert(TABLE_ACCOUNT_DEVICE, null, values);
} else {
return mDB.update(TABLE_ACCOUNT_DEVICE, values, ACCOUNT_DEVICE_SERVER_ID + " =? ",
new String[]{Integer.toString(server_id)});
}
}
Hope it will helps you.

Categories

Resources