Could someone suggest me a way on how to update my apps SQLite database when the content of the parsed JSON file is changed?
I am having a hard time finding the right solution, now I have to clear the cache before the app starts, but the end user obviously won't do that.
I asume changing the table version is not suitable for frequent updates (hourly).
Thanks!
As #KenWolf mentioned this documentation in the comments.
Update a Database:
When you need to modify a subset of your database values, use the update() method.
Updating the table combines the content values syntax of insert() with the where syntax of delete().
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// New value for one column
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
// Which row to update, based on the title
String selection = FeedEntry.COLUMN_NAME_TITLE + " LIKE ?";
String[] selectionArgs = { "MyTitle" };
int count = db.update(
FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);
Change your database version by incrementing by 1 from current value.
It will make possible of updation.
Related
I'm trying to update a table in SQLite android. I have a column called 'quantity' which stores qty of some items, say item1, item2 ...
Now when I purchase item1, I'd definitely want to 'add' the purchased qty to an existing qty of item1.
I searched the web but couldn't find a solution, hence asking this.
My simple code's below:
// This method is used to 'UPDATE' the table 'stock'.
// This method will be used by two fragments,
// 'sale' and 'purchase' fragments.
public int updateData(String cigaretteName,int quantity, int cost, int totalCost) {
// Accessing the database with writable functionality so it can be updated.
SQLiteDatabase db = this.getWritableDatabase();
// Creating content values object to put the new values in existing rows with old values.
ContentValues contentValues = new ContentValues();
contentValues.put(StockEntry.COLUMN_QUANTITY, (StockEntry.COLUMN_QUANTITY + quantity));
contentValues.put(StockEntry.COLUMN_COST, cost);
contentValues.put(StockEntry.COLUMN_TOTAL_COST, totalCost);
// Which row to update, based on the cigarette name.
String selection = StockEntry.COLUMN_CIGARETTES_NAME + " LIKE ?";
String[] selectionArgs = {cigaretteName};
// Updating the table with the new values and then returning the number of rows affected.
return db.update(StockEntry.TABLE_NAME, contentValues, selection, selectionArgs);
}
This isn't working at all, now it doesn't even update the column/row.
contentValues.put(StockEntry.COLUMN_QUANTITY, (StockEntry.COLUMN_QUANTITY + quantity));
Do help guys!
I would suggest simple approach to overcome these kind of SQLite related issues.
Use SQLite Manager which is plugin for FireFox browser
Download from https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
Create your dummy database there
Perform your CRUD operations here
Once everything working fine in SQLite Manager then use same query inside your project.
Above way will save your development time as well as testing.
I need help how to implement rawquery in sqlite. I need to insert a record in to specific row in table. I searched and found that I can achieve this using raw query. I am new to sqlite and don't know how to implement raw query. I got syntax error.
Here is my code
public void insert (String potision, String total, String curent)
{
SQLiteDatabase db = this.getWritableDatabase();
db.rawQuery("INSERT INTO "+Table_Name2+" VALUES(?,?) WHERE ID = ? ", new String[] {total,curent,potision});
}
Here is my syntax error:
SQLiteException: near "WHERE": syntax error (code 1): , while compiling: INSERT INTO item_counts_2 VALUES(?,?) WHERE ID = ?
Help will be appreciated
You are having a syntax error because you added a where clause to an insert.
When you execute an insert, you are adding a row to the database. There is no sense in specifying a row.
If you were updating a row, then, the where clause would be fine, because you have to tell him what row to update.
Also when deleting rows, the where clause is widely used, so that you don't erase the whole table.
Insert: official docs
Update: official docs
Delete: official docs
Note that the docs refer to SQLite, since you are using Android.
You can use update query with ContentValues to update specific row data in your DB like this
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_1, value1);
values.put(COLUMN_2, value2);
return db.update(TABLE_NAME, values, ID + " = ?",
new String[] { String.valueOf(idValue) });
Hope it will help you out.
Don't use where clause with insert query.
If you are inserting a new row to database then where clause is redundant, remove it and it will work fine.
OR,
If you want to update value already exist in database, use update query instead of insert,
for more information visit here.
I'm having some difficulty getting my database updated. Basically the user will input data into two separate places, so we get
Name | Letter | Marks
----------------------------
Dave | Null | 90
Dave | A | Null
which should become
Dave | A | 90
However, nothing is updating. The query works perfectly when I try it in SQLite Manager, so I must be implementing cursor wrong.
public void insertData(String name, int mark_column, String marks) {
String [] columns = new String[] {COL_3, COL_4, COL_5};
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(columns[mark_column], marks);
db.replace(TABLE_NAME, null, contentValues);
//The code above works as desired
String sql = "SELECT NAME, GROUP_CONCAT(LETTER, ', ') AS LETTER," +
"GROUP_CONCAT(MARKS, ', ') AS MARKS FROM " + TABLE_NAME + " GROUP BY NAME";
//This query works in SQLite Manager
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
while(c.moveToNext());
c.close();
}
I have tried various combinations of c.moveToLast, not having c.moveToNext, etc. This method is called in onClick of an Alert Dialog.
Any help is greatly appreciated
Regarding the cursor:
I don't see anything wrong with your query. If you aren't "seeing" any results in your app, it's likely because you aren't actually doing anything with the results. They exist in memory in a Cursor object, but that's all; if you want to see anything you have to bind that data to some UI components, or dump it to logcat, or something.
Note that if you were to add code inside of your while loop, you would skip the first row of the cursor because you would have a moveToFirst() call followed immediately by a moveToNext() call. This is how I iterate over a Cursor, and it always works:
if (cusor != null) {
try {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// do something with data in current row
}
} finally {
cursor.close();
}
}
Regarding the update:
You actually aren't doing an update per se, you are doing an insert. SQLiteDatabase.replace() executes this command:
INSERT OR REPLACE INTO tableName(columns) VALUES (values);
This can work as an update only if you have a constraint on the table and the insertion of a new row with these values would violate that constraint (the exact handling for different constraint violations is described here). For the constraint types that I suspect you are expecting, this operation will delete the existing row and insert a new row with these values, but it will not carry over values from the deleted row into the new one. In other words, you need all the combined values in the ContentValues if you expect a replace to occur. It's not like an UPDATE where you can set the values of just certain columns.
You should probably try to do an actual update instead. Make sure to use a proper WHERE clause so you only update rows that matter.
I may be misunderstanding your approach, but the description makes it seem like you are inserting two rows, then trying to update and/or combine them both later. This doesn't make sense to me, and I foresee bugs whereby you have leftover rows that are incomplete and need to be cleaned up. In my opinion, it's better to structure the code so there is one INSERT, and every operation thereafter is an UPDATE on the row of interest.
I've been trying to update on of my column in my database named COLUMN_NAME_PERIOD_END but it doesn't seem to be able to.
String[] endDate = new String[1];
endDate[0] = paraPeriodDetailsPojoObj.getPeriodEndDate();
Log.d("PeriodEnd.onClick()", "Date: " + endDate[0]);
/*UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
*/
sqliteDatabase.update(DBStorage.TABLE_NAME_PERIODSTART, contentValues, DBStorage.COLUMN_NAME_PERIOD_END+"=?", endDate);
No error messages were displayed so I suppose it is my update statement that is having errors. :(
From the docs:
update(String table, ContentValues values, String whereClause, String[] whereArgs)
So, you are putting the array of contentValues (which you don't show, so the problem could be there) into the table defined by TABLE_NAME_PERIODSTART, and selecting which record to update by searching the column defined by COLUMN_NAME_PERIOD_END which must equal endDate.
The way I read your question title I'm under the impression you actually want to update the COLUMN_NAME_PERIOD_END column with the endDate... if that's the case your SQL is incorrect.
Otherwise, some possibilities that leap to mind to look for are:
1) Constraints... do you have a not null field defined and you are trying to update with a null?
2) Your date format from the program is differing from the one in the database
3) There is no matching record for the endDate you are searching for in the DB
I’m using a database helper to update a table with one row and two fields, I have the following code that that sends two phone numbers through.
dbHelper.updateNumbers(newSmsNumber, newVoiceNumber);
and the following method in the helper.
public void updateNumbers(String newSmsNumber, String newVoiceNumber) {
//Update code here
}
Can anyone show me the code I need to add in the method to update the two fields in the database.
Cheers,
Mike.
ContentValues cv = new ContentValues();
cv.put("SMS", newSmsNumber);
cv.put("Voice", newVoiceNumber);
db.update("[table name]", cv, "ID=?", new String[]{Integer.toString(id)});
There are some gaps to fill up though, the table name, and how you identify the entry you want to update (I put a "ID" field there in that example)
Did not run that code, did not really check, but that should give you an idea.