I have a database with multiple tables. One of these tables (sport) is where i have to put a static list of object, each one with an _id, name, logo and an int. The _id will be used by other tables to do some queries (eg. select from "table X" where sport_id = _id), so it shouldn't change overtime (is there a way to update all the reference to this _id if it will change?).
Where should i put the code (i think it will be a simple list of db.insertSport()) to make it add this row only one time (and check if the row number grow, to add the new ones)?
There won't be much row, 50 at the best.
I think I would make a method in the dbHelper to insert that data, then call that method immediately upon app start. I'm making a couple of assumptions here... first that you are shipping this static info with the app and when you want to add more info you will be shipping a new version.
You could store the data as a text file in your assets folder and then read the file in execute a batch insert in the method.
If you set it up right (use insertWithOnConflict and the CONFLICT_IGNORE flag in the method) it will only add the new rows (if any) each time so you can run it every time the app starts and not worry about duplicate data or crashes for constraint violations.
If you only want it to run the once and then again when there is additional info, put a version number in the text file and check that against the previous one (which you can store in SharedPreferences).
EDIT
Example of using insertWithOnConflict:
public long createItem(String yourdata) {
ContentValues initialValues = new ContentValues();
initialValues.put(YOUR_COLUMN, yourdata);
return mDb.insertWithOnConflict(YOUR_TABLE, null, initialValues,
SQLiteDatabase.CONFLICT_IGNORE);
}
You can read up on the SQLiteDatabase class (which has the constants and methods) here
Related
Im receiving throught BLE data stored in an SD Card. This data is organized in multiple text files, with each file corresponding to a date.
When receiving this data on android i want to save it on a SQlite database.
Thought about using the same logic, creating a table for each day. My question is if its possible to automatically create tables depending on the number of days that is going to be transfered. After some research i found how to add new tables using the onUpgrade method and changing the database version, but this seems only possible by changing the database version manually.
Another option would be by creating a single table for all the data, and add the date as a column.
Any feedback is valuable!
Typically you would use a single table with the date as a column.
It would be possible to dynamically create tables, if they don't exist outside of the onUpgrade method. For each date/file you could, when receiving the file and before loading/inserting the data, either :-
use CREATE TABLE IF NOT EXISTS the_table_with_a_name_that_relates_to_the_date (the_column_definitions)
i.e. if the table exists then the above is effectively a NOOP.
use something like (the below assumes this method is in the DatabaseHelper)
:-
public bolean checkAndAddTable(String tableName) {
boolean rv = false;
SQLiteDatabase = this.getWriteableDatabase();
Cursor csr = db.query("sqlite_master",null,"name=? AND type='table'",new String[]{tableName},null,null,null);
if (csr.getCount() < 1) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + "(......SQL TO CREATE THE COLUMN DEFINITIONS......)");
rv = true;
}
csr.close();
return rv;
}
Note the code is in-principle code ans has not been run or tested and my therefore have some errors.
However, extracting the data from multiple tables would/should need to check if the table exists, to see if data can be extracted which would incur additional processing/complications (e.g. what to do if it doesn't exist).
I was just wondering if it's possible to just input/update a single value into an SQLiteDatabase (as opposed to an entire row).
The SQLiteDatabase API on the Android developer site makes it sound like you can only insert one row at a time (which erases previous information).
An alternative I've been thinking of is to copy the contents of the entire row into an array, alter a value in the array, and then insert the values of the array as an update row in the SQL Database. Does anyone have a more efficient and less roundabout solution?
The SQLiteDatabase API on the Android developer site makes it sound like you can only insert one row at a time (which erases previous information).
A standard SQL INSERT statement does not erase "previous information". It adds a new row to a table.
I was just wondering if it's possible to just input/update a single value into an SQLiteDatabase (as opposed to an entire row).
By definition, it is not possible to insert a single value into a table. You insert rows into a table. Any columns that you do not provide values for in your INSERT statement need to either allow NULL values or have default values defined on the table.
A SQL UPDATE statement, however, can update a single column in a row. This is true whether you use update() or execSQL() on SQLiteDatabase to update that row.
then insert the values of the array as an update row in the SQL Database
A standard SQL INSERT statement does not update a row. It adds a new row to a table.
I am working on an android application using android:minSdkVersion="14". The application receives data as JSON from a server. The data received need to be added to an sqlite table. If a row exists, all fields except for two have to be updated. If a row does not already exist in the table, it has to be inserted. I am looking for the most efficient way as regards performance.
The function insertwithonCoflict() has been considered but it is not an option since in case of update, it updates all the fields including the two that should not be updated.
The function replace() is also not suitable.
I would opt for a SELECT to check if the row exists and then an INSERT or UPDATE but I was wondering if I could optimize the procedure somehow .
Two approaches:
Change the database structure so that the table has only the server data. Put local data (the two columns) in another table that references the server data table. When updating, just insert to the server data table with "replace" conflict resolution.
Do the select-insert/update logic.
For performance in any case, use database transactions to reduce I/O. That is, wrap the database update loop in a transaction and only commit it when you've done with everything. (In case the transaction becomes too large, split the loop into transaction chunks of maybe a few thousand rows.)
A nice solution I use is as follows:
long id = db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
if(id!=-1) db.update(TABLE, contentValues, "_id=?", new String[]{String.valueOf(id)});
This ensures the row exists and has the latest values.
I have problems in updating rows in SQLite database in my Android application. It works successfully only, if I update it two times. But when I try to do it on the third time, it doesn't update the same row anymore.
LogCat doesn't show any exceptions. db.update() returns '1'.
I've searched similar issues on StackOverflow and the web. People advic]sed to remove db.close(); from database-helper, because I call it several times, or to use db.update method instead of db.rawQuery() or db.execSQL().
I also tested my query in SQLite client, and it works as it's supposed to.
Here is code of simple database-helper method:
public int updateEventDoneMark(Event event)
{
ContentValues args = new ContentValues();
args.put("completed", event.getCompleted());
return db.update("Event", args, "id" + "='" +event.getId() + "'", null);
}
Is there some SQLite-related issue I should know while I update one database entry several times in a row?
What does your content provider update and URI match look like?
Typical Content providers have a URI for each Table/View for a single row where _id is passed as a where_argument and a URI for multiple rows which uses where and where_arguments to select the rows to be updated.
Also it looks like you update by id. Android really want the id column named "_id", although I don't think is currently your issue, but it really depends on the URI it's using. Content Providers are usually coded with the _id and select by the column for a single row based on _id. That's why I want to see content provider. Your also selecting by the id yourself, this doesn't seem normal, although it could be accomplished, but not the norm. Typically the where part is something like 'colunm name = ?" and the next parameter where_arguments is a string array containing the value to replace the '?'.
Hope this helps.
I am wondering how can I insert an element at the beginning of the data base? I want to do this because:
a) I want to display the elements (ListView) as 'last-inserted on top and first-inserted on the bottom' (like a stack)
b) I want to limit the amount of elements in my db. When a new element is added (over the limit) I can put the new one (at the beginning) and delete the last one. (Don't know yet how to delete the last element).
I was searching for a solution but I am starting to wonder I have any control of how the element are inserted. If not I was thinking about displaying the database from end to bottom. But don't actually know how to do it since the cursor is always set at the beginning of the db. If could achieve this I can solve b) by deleting the first element (again don't know how to achieve this yet).
Every row of every SQLite table has a 64-bit signed integer key that uniquely identifies the row within its table. This integer is usually called the "rowid"
To get last inserted at top and first inserted at bottom....
SELECT * from mytable order by ROWID desc;
Read more about ROWID here
And, to delete the oldest:
DELETE from mytable WHERE ROWID = (SELECT MIN(ROWID) FROM mytable);
If you use the ROWID, you do not have to modify your existing table. And, the value of ROWID is guaranteed.
You can store a timestamp (as a new field) when you insert a record into your database. Then you delete the oldest record you can find if it is over the limit (e.g. using MAX SQL keyword). You can display the records in reverse-chronological order by sorting DESC with your timestamp field.