Avoid sqliteAssetHelper to log error - android

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.

Related

Show error if data cannot be inserted

I need to handle an error when non-unique data is inserted into the database. I have this code:
try {
handler.addBookmark(new BookmarkModel(idBrand, brand, desc, types, detail, image));
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
}catch (SQLiteException e){
e.printStackTrace();
Toast.makeText(this, "Failed", Toast.LENGTH_LONG).show();
}
I insert like this:
public long addBookmark(BookmarkModel bookmark) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, bookmark._id); // Must Unique
values.put(KEY_BRAND, bookmark.brandName);
values.put(KEY_DESC, bookmark.descTerm);
values.put(KEY_TYPE, bookmark.type);
values.put(KEY_DETAIL, bookmark.detail);
values.put(KEY_IMAGE, bookmark.image);
return db.insert(TABLE_BOOKMARK, null, values);
//db.close();
}
Logcat of the error that occurs:
android.database.sqlite.SQLiteConstraintException: column id is not unique (code 19)
The data was not inserted, but I was unable to show the error message. How can I show the toast to let the user know the insert failed?
Do not set _id yourself. This line should be gone:
values.put(KEY_ID, bookmark._id); // Must Unique
If your table schema sets it up correctly (_id INTEGER PRIMARY KEY) then this is auto incremented long value. Nothing you should touch on insert.
You should look into the insertOrThrow() method which will throw an SQLiteConstraintException if this occurs.
Then, you can put your insert into a try/catch block:
try{
db.insertOrThrow(table, columnHack, values);
} catch (SQLiteConstraintException e){
Toast.makeText(context, "Unable to insert values.", Toast.LENGTH_SHORT).show();
}
I got a solution. just set an id to PRIMARY KEY AUTOINCREMENT and set 1 text UNIQUE . for methode that handle an error, i use insertOrThrow and use it with try-catch .

How create table behaves in transactions?

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
}

Android SQLite rawQuery giving trouble

There's this method which i've created to know if a contact exists in my Sqlite database.
public Cursor doesContactExist(String name)
{
return db.rawQuery("select * from contacts where name = ?; ", new String[] {name});
}
But whenever it is called from another activity it crashes only at this point....
if(db.doesContactExist(name)==null){ <== crashes here
try {
db.open();
db.insertContact(name,cNumber);//name and number are Strings
listItems.add(name); //a List View array
db.close();
adapter.notifyDataSetChanged(); //adapter for ListView
}
catch (Exception e) {
//some code }
}
According to me the rawQuery is having some troulble, especially the sql String in it.
Any help please?
you try to make a select before your database is open:
if(db.doesContactExist(name)==null){ <== it is closed here
try {
db.open(); <== open the db here
change it to:
db.open();
if(db.doesContactExist(name)==null){
try {
I think it might help you..
db.open();
if(db.doesContactExist(name)==null)
{
try
{
// Your Code Here..
}
}
and in Database Class
public Cursor doesContactExist(String name)
{
return db.rawQuery("SELECT * FROM contacts WHERE name=?", new String[ {name.toString()});
}
use db.open() method before using any database function because it will open your connection with database.. and at last don't forget to close database like db.close() and if you are using Cursor anywhere in code please close this also. it not generates any error but it gives you warnings. :)

Android database overWriting same row over and over

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.

SQLiteDatabase.insertOrThrow doesn't throw but not data is inserted

I'm trying to get familiar with Android and its database API.
I've created a class that inherits from SQLiteOpenHelper and this
is how I create the table in the database
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE " + FUELS_TABLE_NAME + " ("
+ "_ID INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "DATE_OF_FUELS DATE DEFAULT CURRENT_TIME,"
+ "SELLER_POSITION TEXT DEFAULT 'unknown',"
+ "AMOUNT REAL"
+ ");"
);
} catch (SQLException e) {
Log.e(DATABASE_NAME, e.toString());
}
}
The function used to add data to the DB is the following implemeneted within
the same class is
public void addNewFuel(float amount) {
// Create the content to insert into the database
ContentValues newEntry = new ContentValues();
newEntry.put("amount", amount);
// Get database handler
try {
db = getWritableDatabase();
} catch (SQLException e) {
Log.e(DATABASE_NAME, e.toString());
return;
}
// Begin transaction and insert data
long returnedValue;
db.beginTransaction();
try {
returnedValue = db.insertOrThrow(FUELS_TABLE_NAME, null, newEntry);
Log.v(DATABASE_NAME, "return value " + returnedValue);
} catch (SQLException e) {
Log.e(DATABASE_NAME, e.toString());
} finally {
db.endTransaction();
}
db.close();
}
but apparently no data is added. The returnValue is always 1. The method doesn't throw,
and when I pull out the DB with adb and look at it's content is totally empty.
I just can't understand what I'm missing.
Any suggestion would be appreciated.
Thanks,
S
McStretch's answer is incorrect. getWritableDatabase() does not create a transaction for your code, the quoted line from the docs is referring to transactions being used for the onCreate and onUpgrade methods meaning that you don't need to add transaction code in those methods. You still need add transaction code for any other method that requires transactions.
emitrax's code is not working correctly as db.setTransactionSuccessful() is not being called which means the transaction will be rollbacked by db.endTransaction().
See benritz's answer for the correct solution. This answer is incorrect, but I'm unfortunately not able to delete it since it's an accepted post.
/******* NOT CORRECT!!
Since you're inheriting from SQLiteOpenHelper, your call to getWritableDatabase() already starts a DB transaction. From the SQLiteOpenHelper API:
Transactions are used to make sure the
database is always in a sensible
state.
Thus you don't need to call db.beginTransaction() and db.endTransaction(). Those extraneous transaction calls are messing up your inserts. I plugged the same scenario into my project and found that the same index (6 in my case), was returned when using those transaction methods. When I remove the calls I get my desired results (multiple records inserted).
NOT CORRECT!! *******/

Categories

Resources