my app contain sqlite db, my question: is there a method or a way to save and view the history of a specific column if it has changed or updated ? my app is basically for input and output for items. everything is working fine but I want to keep track of the history of the quantity of the item and I cant figure it out the code of output an item :
boolean updateexistItemOutput(String itemname, String itemtype ,String itemsTypeOut, double outputQty, double total, double profit, double profitMultiple, double totalProfitSingle,
double totalProfitMultiple, String lastUpdated, String inOrOut, String notes) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(column_name, itemname);
contentValues.put(column_outputquantity, outputQty);
contentValues.put(column_itemsType,itemtype);
contentValues.put(column_total, total);
contentValues.put(column_profitSingle, profit);
contentValues.put(column_profitMultiple, profitMultiple);
contentValues.put(column_TotalprofitSingle, totalProfitSingle);
contentValues.put(column_TotalprofitMultiple, totalProfitMultiple);
contentValues.put(column_updateDate, lastUpdated);
contentValues.put(column_inOurOut, inOrOut);
contentValues.put(column_notes,notes);
contentValues.put(column_itemsTypeOut, itemsTypeOut);
return sqLiteDatabase.update(table_Name, contentValues, column_name + "=?", new String[]{itemname}) > 0;
}
I think the common way is create a new table History that record the data change.
Every time you change the data should insert a new record into the History table.
Related
I'm trying to have an SQLite database in android but I have a problem with that:
I'm trying to update the text value in the "response" column with id 0. The first problem I had was that the string I was using for the update used an apostrophe (') and it had syntax errors because sql closes the string with an '. So I now am using a prepared sql statement for that. The problem now is that the long that is returning gives a -1, so that means that no rows were effected. So how can I update my current string to the row with id=0?
Note: the first string also has an ' but was added using the addData funtion and it didn't give any errors just using db.insert, is that the problem, should I replace all my code with prepared statements?
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public long updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE json_response SET response=? WHERE ID='0'";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, newName); // matches second '?' in sql string
long rowId = statement.executeInsert();
return rowId;
}
I have not used prepared statements much so I can't say why that is not working, but why not use the db.update() method? It takes ContentValues as an argument similar to tour addData() method. Give this a shot.
public int updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("json_response",newName);
int rows = db.update(TABLE_NAME, cv, "ID=0", null);
return rows;
}
[EDIT] update() returns an integer representing the number of rows affected instead of which row was affected. Keep that in mind as your variable name rowId implies that is not what you are looking for.
[EDIT 2] And no, there is no problem with the addData() method that I can see. The apostrophe that was added did not cause an error because ContentValues parameterizes the string values before adding them into the database. Basically, all SQL-like syntax will be ignored when inserting values, which is great for security reasons.
The problem is, I think, that WHERE ID='0' will always fail; what you want is WHERE ID=0
I have making project with DB and I have layout with two edittexts in that edittext on activity start I load one column from my DB and display it and in other edittext is text with I want to find specific row in DB table.
When I find that row I need to edit some values in this row. Here is my updatecode in DBadapter.java
// Change an existing row to be equal to new data.
public boolean updateRow(long containercode_row, String lkwnummer,String uniqueid, String containerbarcode,
String timein, String timeout, String howout, String latitudein,
String longitudein, String latitudeout, String longitudeout, String status) {
String where = KEY_CONTAINERBARCODE + "=" + containercode_row;
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_LKWNUMMER, lkwnummer);
newValues.put(KEY_UNIQUEID, uniqueid);
newValues.put(KEY_CONTAINERBARCODE, containerbarcode);
newValues.put(KEY_TIMEIN, timein);
newValues.put(KEY_TIMEOUT, timeout);
newValues.put(KEY_HOWOUT, howout);
newValues.put(KEY_LATITUDEIN, latitudein);
newValues.put(KEY_LONGITUDEIN, longitudein);
newValues.put(KEY_LATITUDEOUT, latitudeout);
newValues.put(KEY_LONGITUDEOUT, longitudeout);
newValues.put(KEY_STATUS, status);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
I need to find row throught KEY_CONTAINERCODE value but I don't know how to make this code in activity where I want to find that row and edit it?
you can update your values by making a method in CommonUtill file like this:
public int updateRecords(String table, ContentValues values,
String whereClause, String[] whereArgs) {
int a = db.update(table, values, whereClause, whereArgs);
return a;
}
there is no need for creating a separate method for this for good practices.
I am trying to update a specific column in my record within SQLite - the object has various attributes, but I just want to update a single field within that row. Here are my codes:
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(EMAIL, email);
args.put(IS_FAV, isFavorite);
int i = db.update(TABLE_FAVORITES, args, EMAIL + "=" + email, null);
return i > 0;
}
I am using the email for my where clause, i.e update record from favorites, set isFavorite to (given value) where email is (passed in value).
There is a problem with my query, which was caught by logcat, as shown below
android.database.sqlite.SQLiteException: near "#sjisis": syntax error (code 1): , while compiling: UPDATE Favorites SET email=?,isFavorite=? WHERE email=sjkshs#sjisis.com
Can anyone help me identify what is wrong with my codes to produce this error?
P.S my FavoriteObject class has other attributes other than just email and isFavorite, but in this case I am not trying to update them at all
Try to make email in where clause be argument too, i try to change your code but didn't test yet :
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(EMAIL, email);
values.put(IS_FAV, isFavorite);
//add arguments for where clause
String[] args = new String[]{email};
int i = db.update(TABLE_FAVORITES, values, "EMAIL=?", args);
return i > 0;
}
Looks like it's complaining about the email address, perhaps the #.
try
int i = db.update(TABLE_FAVORITES, args, EMAIL + "= ' " + email + "'", null);
ie. single quotes around the email address.
I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:
METHODS FOR ANDROID SQLITE DATABASE QUERY:
public void updateUser(String newProfession, String newCountry, String sx, String ag) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
Cursor cursor = db.rawQuery(query, null);
cursor.close();
db.close();
}
public int countAll() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
db.close();
return cnt;
}
CALLING THE METHODS
public void updateUsersClicked(View view) {
int allData = db.countAll();
for (int i = 0; i < allData; i++) {
db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
System.out.println("T H I S I S T H E R E S U L T: " + i);
}
}
Use execSQL() and not rawQuery() for updates.
rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.
Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.
You don't need to do the for loop
a single QSL "Update" query is enough if you want to update All the female with age 30.
If you are new to SQL you can view a simple example here:
Simple SQL Update example
If you want to do something else - please edit your question
I am using SQLIte in my app.While updating contact,i just want to get a specific item changed while keeping others same e.g if there are 3 items in the row i.e name,number,address I want to update only name while keeping the others 2 same.This the code:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
values.put(KEY_TIME, contact.getTime());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
Please tell me how to do it?Thanks in advance.