I've been stuck on this for a few hours now.
I have an Activity that calls a method to write some values into a database, it works, except for the fact that it overWrites the same row in the database over and over again. My database table does have an _id that is set to autoincrement.
try {
myDataBase.beginTransaction();
myDataBase.insert("camera_notes", null, camera_data);
myDataBase.setTransactionSuccessful();
} catch (SQLException e) {
Log.i(TAG,"#################Exception thrown from updateDataBaseNotes:################ "+e);
e.printStackTrace();
}
finally{
myDataBase.endTransaction();
}
close();
I have just tried adding the transaction code, but no luck so far.
Does anyone have any ideas or can point me in the right direction?
Thanks
ContentValues camera_data = new ContentValues();
camera_data.put("note_title", title);
camera_data.put("note_text", note);
camera_data.put("image_source", image_src);
camera_data.put("sound_source", recording_src);
Is that the only row? If so, it sounds like you're destroying the entire table each time before you're inserting the row.
Related
Hi guys i'have problem with this little block of code
// Insert a new contact in database
public void insertInSignature(String TITLE_SI) {
try {
// Open Android Database
db = databaseHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("TITLE_SI", TITLE_SI);
db.insert("DELIVERY_SLIP", null, initialValues);
} catch (SQLException sqle) {
Log.e(TAG, "insertUser Error");
Log.e(TAG, "Exception : " + sqle);
} finally {
// Close Android Database
databaseHelper.close();
}
}
I have unique constraint on my table "DELIVERY_SLIP
So , when i'm trying to insert some row which already exist , it return some error like "Oh shit , you're inserting the same , i'm sorry men , i can't do it"
http://cdn.imghack.se/images/3b51afd07d1f1a8bd021c9e9dfc57e98.png
Here my log
It's this line
databaseHelper.close();
When database helper close , this return the log.
I just want to avoid to log it, I already tested with a tryCatch on sqliteConstraintException
But, nothing worked.
Thanks by advance
Instead of insert(), use insertWithOnConflict() with some conflict resolution algorithm appropriate for your use, such as SQLiteDatabase.CONFLICT_IGNORE.
I am using transactions to insert record to my database. Can you please tell me whether this is the right way to get total inserted record (return by numrow)? Also, in the code below, if some insert fails, will it continue to next insertion or will exit (I didn't use endTransaction in Catch block)?
int numrow = 0;
try{
db.beginTransaction();
for(mylibman cn : insertlist){
ContentValues values = new ContentValues();
values.put(KEY_LIBID, cn.getLibid());
values.put(KEY_NAME, cn.getBookname());
db.insertWithOnConflict(TABLE_NAME, null, values,SQLiteDatabase.CONFLICT_IGNORE);
numrow++;
}
db.setTransactionSuccessful();
}catch (Exception e) {
} finally {
db.endTransaction();
}
return numrow;
you should check like this
int numrow = 0;
try{
db.beginTransaction();
for(mylibman cn : insertlist){
ContentValues values = new ContentValues();
values.put(KEY_LIBID, cn.getLibid());
values.put(KEY_NAME, cn.getBookname());
//do like this
long insertedId=db.insertWithOnConflict(TABLE_NAME, null, values,SQLiteDatabase.CONFLICT_IGNORE);
if(insertedId!=-1)
{
numrow++;
}
}
db.setTransactionSuccessful();
}catch (Exception e) {
} finally {
db.endTransaction();
}
return numrow;
Your code will also count records that were ignored.
insertWithOnConflict returns the rowid of the inserted record, or -1, so you have to check for that:
if (db.insertWithOnConflict(TABLE_NAME, null, values,
SQLiteDatabase.CONFLICT_IGNORE) != -1)
numrow++;
The insertWithOnConflict function does not throw an exception if a record is not inserted due to a conflict. However, it will throw if there is some other error, such as an unknown column name, or a read-only database.
You should not blindly ignore exceptions; just use try/finally:
db.beginTransaction();
try {
for (...) {
...
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Non of the answers here reflect the documentation:
"returns:
the row ID of the newly inserted row OR the primary key of the existing row if the input param 'conflictAlgorithm' = CONFLICT_IGNORE OR -1 if any error"
Since the author wants to know the 'inserted' columns, both answers are wrong. The number inserted rows could be 0, as they already exist. However "CONFLICT_IGNORE" will make insert return the existing primary key, so the numrow will be the rows you 'tried' to insert and didn't fail, but not the rows 'inserted'.
You might have to use the flag "SQLiteDatabase.CONFLICT_ABORT" or "SQLiteDatabase.CONFLICT_FAIL" depending on what and how you insert.
Source: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insertWithOnConflict%28java.lang.String,%20java.lang.String,%20android.content.ContentValues,%20int%29
i am working on sqlite insertion using contentvalues with transaction . The following code does not generate any exception however the data is not inserted.
Did i miss somethings ? Thanks.
public boolean addRecord(Rec rec) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
ContentValues values = new ContentValues();
values.put(KEY_ID, rec.get());
// Inserting Row
try {
db.insertOrThrow(TABLE_RECORDS, null, values);
} catch (SQLException e) {
e.printStackTrace();
}
db.endTransaction();
db.close();
return true;
}
After calling beginTransaction, you must call setTransactionSuccessful to ensure that the transaction gets committed. Without that call, any changes in the transaction are rolled back.
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
This particular construction ensures that any exception in the actual database code will result in an rollback.
(If you get an exception, it is a bad idea to just swallow it; the entire function must fail.)
I run two transactions.
In first transaction the table test is created,
but then I say rollback for this transaction.
I think that then the table test should have been created or not,
but not something between.
Then I run the other transaction to test what has happened:
I insert one row in the table test.
That seems work in program but when I go to sqlite prompt,
I do not see the table test there when I say the command ".schema".
Can someone tell what is happening?
Output of my code is:
"Insert ok."
try
{
db.beginTransaction();
String s =
"CREATE TABLE test(id INTEGER PRIMARY KEY AUTOINCREMENT ,age INTEGER)";
db.execSQL(s);
}
catch (Exception e)
{
System.out.println("Exception 1:"+e);
}
finally
{
db.endTransaction();
}
try
{
db.beginTransaction();
db.execSQL("INSERT INTO test VALUES(NULL,22)");
db.setTransactionSuccessful();
System.out.println("Insert ok.");
}
catch (Exception e)
{
System.out.println("Exception 2:"+e);
}
finally
{
db.endTransaction();
}
Can someone tell what is happening?
It's normal behaviour. Your table wasn't created because you didn't commit TRANSACTION as well as your insert wasn't performed. Reason why you are getting result
System.out.println("Insert ok.");
is that execSQL() method throws SQLException only in the case if your query string is invalid / broken. And also you can't use execSQL() for inserting. You can use it only for altering tables.
Execute a single SQL statement that is NOT a
SELECT/INSERT/UPDATE/DELETE.
Solution:
Since execSQL() is void type you need to use API method insert() to test result.
long rowId = db.insert("test", <nullColumnHack>, values);
if (rowId < 0) {
// error
}
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.