Easiest way to enter more than one rows in a table - android

When the first time i am running the app, i want to create a table and enter some rows into the table. For doing this, i wrote this bit of code and it is working fine:
//Creating the table
db.execSQL(MRM_BOOKING_LOGIN_TABLE_CREATE);
//Setting the values in the table
ContentValues contentValuesLogin = new ContentValues();
contentValuesLogin.put(USER_ID, "asdf");
contentValuesLogin.put(PASSWORD, "1234");
//Inserting a row in the table
db.insert(MRM_BOOKING_LOGIN_TABLE, null, contentValuesLogin);
But i want to enter at least 15 to 20 rows in the table. Is it a good idea that every time after inserting one row, i will clear the ContentValues object (or create another object of ContentValues) and enter another row in the newly created table? In this way, the lines of code will increase a lot as well. I am sure there might be some other better alternative way to do the same. Please suggest
Regards,

I think, the only way to insert multiple records via db.insert is to use a loop. Combine it together with SQLite Transaction and it will speed up the process.

A sample code:
try {
// open the database
db.beginTransaction();
for (your objects) {
ContentValues cv = new ContentValues();
cv.put(COL1, obj.p1);
cv.put(COL2, obj.p2);
//.....
long id = db.insertOrThrow(DATABASE_TABLE, COL_Id, cv);
}
db.setTransactionSuccessful();
} catch (Exception e) {
throw e;
} finally {
db.endTransaction();
// close database
}

You can insert multiple rows using ContentResolver.bulkInsert (Uri url, ContentValues[] values).
More information can be had from here:
Insertion of thousands of contact entries using applyBatch is slow
Hope this will help you.

Related

Content Provider - Updating All Rows and Columns

I have an array of ContentValues[] called cv, which go into my SQLite database. To keep it really simple, my database has these 3 columns (An AutoIncremented ID for each row, the day, and humidity.) The Database has 3 rows. Here is an example of data added to a single row.
ContentValues cv = new ContentValues();
cv.put(WeatherContract.WeatherData.COLUMN_DAY_OF_WEEK, day);
cv.put(WeatherContract.WeatherData.COLUMN_HUMIDITY, humidity);
This loops 3 times and each ContentValue is put into my ContentValue array before a bulk insert is made into my database.
I have a Job that grabs new data from a server every five minutes. So I need this new data to replace the old and am having trouble with the Syntax. I get right up to the point where I have ContentValues[] jsonResults with new data and then am a bit confused. How can I update ALL of the rows in my table? Do I need to loop through the contentResolvers update method:
for (int i =0; i<jsonResults.length;i++){
context.getContentResolver().update(weatherQueryUri,jsonResults[i],null,null);
}
If so, what am I placing in my where and selectionArgs clauses instead of null? Or do I keep it null?
After going through the ContentProvider, here is my database method for the actual insertion:
public void updateRow(ContentValues weatherValue,String where, String selection){
mDb.update(WeatherContract.WeatherData.TABLE_NAME,weatherValue,null,null);
}
Thank you!
Well, I am not so sure if my solution works well but you can give it a try.
In order to replace the old data with the new ones, I'd first perform delete() then bulkInsert() on your ContentResolver object. This way you dont have to loop thru the jsonResults.
if (jsonResults != null && jsonResults.length != 0) {
/* Get a ContentResolver object to help delete and insert data */
ContentResolver contentResolver = context.getContentResolver();
/* Delete old data */
contentResolver.delete(weatherQueryUri,null,null);
/* Insert our new data into contentResolver */
contentResolver.bulkInsert(weatherQueryUri, jsonResults);
}

How to bind values to SQLiteStatement for insert query?

Insertion code using SQLiteStatement usually looks like this,
String sql = "INSERT INTO table_name (column_1, column_2, column_3) VALUES (?, ?, ?)";
SQLiteStatement statement = db.compileStatement(sql);
int intValue = 57;
String stringValue1 = "hello";
String stringValue2 = "world";
// corresponding to each question mark in the query
statement.bindLong(1, intValue);
statement.bindString(2, stringValue1);
statement.bindString(3, stringValue2);
long rowId = statement.executeInsert();
Now this works perfectly fine but the issue I find here is that I have to be very careful about binding correct data to corresponding indexes. A simple swap of index will give me an error.
Also let's say in future my column_2 gets dropped from the table, then I would have to change all the indexes after the column_2 index otherwise the statement won't work. This seems trivial if I just have 3 columns. Imagine if a table has 10-12 (or even more) columns and column 2 gets dropped. I'll have to update the index of all the subsequent columns. This whole process seems inefficient and error prone.
Is there an elegant way to handle all this?
Edit : Why would I want to use SQLiteStatement ? Check this :Improve INSERT-per-second performance of SQLite?
Insertions can be done with ContentValues:
ContentValues cv = new ContentValues();
cv.put("column_1", 57);
cv.put("column_2", "hello");
cv.put("column_3", "world");
long rowId = db.insertOrThrow("table_name", null, cv);
But in the general case, the most correct way would be to use named parameters. However, these are not supported by the Android database API.
If you really want to use SQLiteStatement, write your own helper function that constructs it from a list of columns and takes care of matching it with the actual data. You also could write your own bindXxx() wrapper that maps previously-saved column names to parameter indexes.
You can use ContentValues with beginTransaction into SQLite that is quite easy as well as faster then prepared statements
For this you have to create ContentValues Array previously or create Content values object into your loop. and pass into insert method .this solution solve your both of problem in one.
mDatabase.beginTransaction();
try {
for (ContentValues cv : values) {
long rowID = mDatabase.insert(table, " ", cv);
if (rowID <= 0) {
throw new SQLException("Failed to insert row into ");
}
}
mDatabase.setTransactionSuccessful();
count = values.length;
} finally {
mDatabase.endTransaction();
}

Avoid duplicate entries in SQLite

I am writing a small application in android to store basic details about person using SQLite.
I insert data using this function
public void insertData(String user,String p_no,SQLiteDatabase db)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
The above function allows duplicate names to be stored.
So I wrote a function that will first check whether a name exits and then enter.
public void insertData(String user,String p_no,SQLiteDatabase db)
{
Cursor resultSet=db.rawQuery("select NAME from MYTABLE where NAME = '"+user+"'",null);
if(resultSet==null)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
else Toast.makeText(context,user+" already exists",Toast.LENGTH_SHORT).show();
}
But the problem is now toast comes up every time I insert meaning even if the row is unique it is not inserted.
Why resultSet is not null even when there is no such row?
It is because RawQuery never returns null cursor, and that's what your checking criteria is, so it is failing always, and trying to add new value in DB.
I am not able to find the documentation where I learned it, but I will update as soon as possible.
You can check if you have values in cursor using -
if(cursor.moveToFirst())
because it is possible to have an empty cursor. Change your check like
if(cursor.getCount() == 0)
this way, if the cursor is not null, you check if it contains something too.
Probably this is not the best way to handle duplicates, in my opinion. You should mark your column as unique, and use insertWithConflict, to decide what to do in case you have already an entry with that value
Check
if (resultset.getCount() == 0)
Also, create Name as unique key to avoid duplicates. Instead of checking it everytime.

How to update only last record of SQLite database in android?

I am using SQLite database in android. I need to update the record based on some condition. But there are multiple records that fulfills the condition, so all records are getting updated. I need to update only last one. Please help me.
Thanks in advance
Here is my code
public void UPDATE_INVOICE(int invoice_id,int owner_id,int vehicle_id,String invoice_date,String invoice_time,String dest,String distance,String validity_date, int qty,String local_var)
{
SQLiteDatabase db=getWritableDatabase();
ContentValues values = new ContentValues();
values.put(INVOICE_NUMBER, invoice_id);
values.put(INVOICE_DATE, invoice_date);
values.put(INVOICE_TIME, invoice_time);
values.put(INVOICE_VALIDITY_DATE, validity_date);
values.put(INVOICE_QTY, qty);
values.put(INVOICE_LOCAL, local_var);
db.update(TABLE_INVOICE_DETAILS, values, INVOICE_OWNER_ID_REF+"="+owner_id+" and "+INVOICE_VEHICLE_ID_REF+"="+vehicle_id, new String[]{});
}
If someone else will find that question, then possible answer is:
update table1 set last_accessed_dt = datetime('now') where _id = (SELECT MAX(_id) FROM table1);

Android/SQLite: Insert-Update table columns to keep the identifier

Currently, I am using the following statement to create a table in an SQLite database on an Android device.
CREATE TABLE IF NOT EXISTS 'locations' (
'_id' INTEGER PRIMARY KEY AUTOINCREMENT, 'name' TEXT,
'latitude' REAL, 'longitude' REAL,
UNIQUE ( 'latitude', 'longitude' )
ON CONFLICT REPLACE );
The conflict-clause at the end causes that rows are dropped when new inserts are done that come with the same coordinates. The SQLite documentation contains further information about the conflict-clause.
Instead, I would like to keep the former rows and just update their columns. What is the most efficient way to do this in a Android/SQLite environment?
As a conflict-clause in the CREATE TABLE statement.
As an INSERT trigger.
As a conditional clause in the ContentProvider#insert method.
... any better you can think off
I would think it is more performant to handle such conflicts within the database. Also, I find it hard to rewrite the ContentProvider#insert method to consider the insert-update scenario. Here is code of the insert method:
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long id = db.insert(DatabaseProperties.TABLE_NAME, null, values);
return ContentUris.withAppendedId(uri, id);
}
When data arrives from the backend all I do is inserting the data as follows.
getContentResolver.insert(CustomContract.Locations.CONTENT_URI, contentValues);
I have problems figuring out how to apply an alternative call to ContentProvider#update here. Additionally, this is not my favored solution anyways.
Edit:
#CommonsWare: I tried to implement your suggestion to use INSERT OR REPLACE. I came up with this ugly piece of code.
private static long insertOrReplace(SQLiteDatabase db, ContentValues values, String tableName) {
final String COMMA_SPACE = ", ";
StringBuilder columnsBuilder = new StringBuilder();
StringBuilder placeholdersBuilder = new StringBuilder();
List<Object> pureValues = new ArrayList<Object>(values.size());
Iterator<Entry<String, Object>> iterator = values.valueSet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> pair = iterator.next();
String column = pair.getKey();
columnsBuilder.append(column).append(COMMA_SPACE);
placeholdersBuilder.append("?").append(COMMA_SPACE);
Object value = pair.getValue();
pureValues.add(value);
}
final String columns = columnsBuilder.substring(0, columnsBuilder.length() - COMMA_SPACE.length());
final String placeholders = placeholderBuilder.substring(0, placeholdersBuilder.length() - COMMA_SPACE.length());
db.execSQL("INSERT OR REPLACE INTO " + tableName + "(" + columns + ") VALUES (" + placeholders + ")", pureValues.toArray());
// The last insert id retrieved here is not safe. Some other inserts can happen inbetween.
Cursor cursor = db.rawQuery("SELECT * from SQLITE_SEQUENCE;", null);
long lastId = INVALID_LAST_ID;
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
lastId = cursor.getLong(cursor.getColumnIndex("seq"));
}
cursor.close();
return lastId;
}
When I check the SQLite database, however, equal columns are still removed and inserted with new ids. I do not understand why this happens and thought the reason is my conflict-clause. But the documentation states the opposite.
The algorithm specified in the OR clause of an INSERT or UPDATE
overrides any algorithm specified in a CREATE TABLE. If no algorithm
is specified anywhere, the ABORT algorithm is used.
Another disadvantage of this attempt is that you loose the value of the id which is return by an insert statement. To compensate this, I finally found an option to ask for the last_insert_rowid. It is as explained in the posts of dtmilano and swiz. I am, however, not sure if this is safe since another insert can happen inbetween.
I can understand the perceived notion that it is best for performance to do all this logic in SQL, but perhaps the simplest (least code) solution is the best one in this case? Why not attempt the update first, and then use insertWithOnConflict() with CONFLICT_IGNORE to do the insert (if necessary) and get the row id you need:
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String selection = "latitude=? AND longitude=?";
String[] selectionArgs = new String[] {values.getAsString("latitude"),
values.getAsString("longitude")};
//Do an update if the constraints match
db.update(DatabaseProperties.TABLE_NAME, values, selection, null);
//This will return the id of the newly inserted row if no conflict
//It will also return the offending row without modifying it if in conflict
long id = db.insertWithOnConflict(DatabaseProperties.TABLE_NAME, null, values, CONFLICT_IGNORE);
return ContentUris.withAppendedId(uri, id);
}
A simpler solution would be to check the return value of update() and only do the insert if the affected count was zero, but then there would be a case where you could not obtain the id of the existing row without an additional select. This form of insert will always return to you the correct id to pass back in the Uri, and won't modify the database more than necessary.
If you want to do a large number of these at once, you might look at the bulkInsert() method on your provider, where you can run multiple inserts inside a single transaction. In this case, since you don't need to return the id of the updated record, the "simpler" solution should work just fine:
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String selection = "latitude=? AND longitude=?";
String[] selectionArgs = null;
int rowsAdded = 0;
long rowId;
db.beginTransaction();
try {
for (ContentValues cv : values) {
selectionArgs = new String[] {cv.getAsString("latitude"),
cv.getAsString("longitude")};
int affected = db.update(DatabaseProperties.TABLE_NAME,
cv, selection, selectionArgs);
if (affected == 0) {
rowId = db.insert(DatabaseProperties.TABLE_NAME, null, cv);
if (rowId > 0) rowsAdded++;
}
}
db.setTransactionSuccessful();
} catch (SQLException ex) {
Log.w(TAG, ex);
} finally {
db.endTransaction();
}
return rowsAdded;
}
In truth, the transaction code is what makes things faster by minimizing the number of times the database memory is written to the file, bulkInsert() just allows multiple ContentValues to be passed in with a single call to the provider.
One solution is to create a view for the locations table with a INSTEAD OF trigger on the view, then insert into the view. Here's what that would look like:
View:
CREATE VIEW locations_view AS SELECT * FROM locations;
Trigger:
CREATE TRIGGER update_location INSTEAD OF INSERT ON locations_view FOR EACH ROW
BEGIN
INSERT OR REPLACE INTO locations (_id, name, latitude, longitude) VALUES (
COALESCE(NEW._id,
(SELECT _id FROM locations WHERE latitude = NEW.latitude AND longitude = NEW.longitude)),
NEW.name,
NEW.latitude,
NEW.longitude
);
END;
Instead of inserting into the locations table, you insert into the locations_view view. The trigger will take care of providing the correct _id value by using the sub-select. If, for some reason, the insert already contains an _id the COALESCE will keep it and override an existing one in the table.
You'll probably want to check how much the sub-select affects performance and compare that to other possible changes you could make, but it does allow you keep this logic out of your code.
I tried some other solutions involving triggers on the table itself based on INSERT OR IGNORE, but it seems that BEFORE and AFTER triggers only trigger if it will actually insert into the table.
You might find this answer helpful, which is the basis for the trigger.
Edit: Due to BEFORE and AFTER triggers not firing when an insert is ignored (which could then have been updated instead), we need to rewrite the insert with an INSTEAD OF trigger. Unfortunately, those don't work with tables - we have to create a view to use it.
INSERT OR REPLACE works just like ON CONFLICT REPLACE. It will delete the row if the row with the unique column already exists and than it does an insert. It never does update.
I would recommend you stick with your current solution, you create table with ON CONFLICT clausule, but every time you insert a row and the constraint violation occurs, your new row will have new _id as origin row will be deleted.
Or you can create table without ON CONFLICT clausule and use INSERT OR REPLACE, you can use insertWithOnConflict() method for that, but it is available since API level 8, requires more coding and leads to the same solution as table with ON CONFLICT clausule.
If you still want to keep your origin row, it means you want to keep the same _id you will have to make two queries, first one for inserting a row, second to update a row if insertion failed (or vice versa). To preserve consistency, you have to execute queries in a transaction.
db.beginTransaction();
try {
long rowId = db.insert(table, null, values);
if (rowId == -1) {
// insertion failed
String whereClause = "latitude=? AND longitude=?";
String[] whereArgs = new String[] {values.getAsString("latitude"),
values.getAsString("longitude")};
db.update(table, values, whereClause, whereArgs);
// now you have to get rowId so you can return correct Uri from insert()
// method of your content provider, so another db.query() is required
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Use insertWithOnConflict and set the last parameter (conflictAlgorithm) to CONFLICT_REPLACE.
Read more at the following links:
insertWithOnConflict documentation
CONFLICT_REPLACE flag
for me, none of the approaches are work if I don't have "_id"
you should first call update, if the affected rows are zero, then insert it with ignore:
String selection = MessageDetailTable.SMS_ID+" =?";
String[] selectionArgs = new String[] { String.valueOf(md.getSmsId())};
int affectedRows = db.update(MessageDetailTable.TABLE_NAME, values, selection,selectionArgs);
if(affectedRows<=0) {
long id = db.insertWithOnConflict(MessageDetailTable.TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
Use INSERT OR REPLACE.
This is the correct way to do it.

Categories

Resources