How to avoid inserting duplicate's into SQLite data base? - android

I am getting contact information from server when i login through account. i am storing those information in SQLite, when user login second time, I don't want to same duplicate contact inserting again into SQLite.
i tried like this but not working
boolean exist= contact_db.CheckItem(entry.getUser());
if(!exist) {
// insert
}else {
// don't insert
}
code in DB class
Cursor mCursor = database.query(ContactsDB.TABLE_CONTACTS, allColumns,
ContactsDB.CONTACT_USERID + "= ' " + name +"'" , null, null, null, null);
if (mCursor != null && mCursor.moveToFirst())
return false;
else return true;
How to avoid the duplicates while inserting the contacts into data base?

Better would be to create a UNIQUE index for that column using UNIQUE Keyword. An example can be found here and also a simpler one can be found here.
After creating table you have to create a UNIQUE INDEX for row as,
CREATE UNIQUE INDEX idx_something ON Table_name
(column_name_1, column_name_2,....);

Check the database for the information.
If the data is present in the database don't do anything if not insert the information into the database

Related

deleting one duplicate row in sqlite

I wish to just delete one duplicate row in here (For example, Jim 21)
SQLiteDatabase myDataBase=this.openOrCreateDatabase("Users",MODE_PRIVATE,null);
myDataBase.execSQL("CREATE TABLE IF NOT EXISTS users (name VARCHAR,age INT(3))");
myDataBase.execSQL("INSERT INTO users(name,age) VALUES ('Rob', 34)");
myDataBase.execSQL("INSERT INTO users(name,age) VALUES ('Nat', 22)");
myDataBase.execSQL("INSERT INTO users(name,age) VALUES ('Jim', 21)");
myDataBase.execSQL("DELETE FROM users WHERE name='Jim'");
Cursor c=myDataBase.rawQuery(" SELECT * FROM users", null);
int nameIndex=c.getColumnIndex("name");
int ageIndex=c.getColumnIndex("age");
c.moveToFirst();
while (c!=null){
Log.i("name",c.getString(nameIndex));
Log.i("age",Integer.toString(c.getInt(ageIndex)));
c.moveToNext();
}
I have tried this
myDataBase.execSQL("DELETE FROM users WHERE name='Jim' LIMIT 1");
But it is throwing a syntax error. I know LIMIT is not syntactically allowed in android. So how do I just delete one record of Jim when there are duplicates?
Thank you.
Limit will not work with Delete query,it's only for Select number of record
Update the query
myDataBase.execSQL("DELETE FROM users WHERE name='Jim'");
you can add more condition for remove specific records
myDataBase.execSQL("DELETE FROM users WHERE name='Jim' AND age=21 ");
There are several ways to achieve this. However, I would suggest to put a unique constraint on your name field.
myDataBase.execSQL("CREATE TABLE IF NOT EXISTS users (name text unique not null, age INT(3))");
Now for creating new entries in your users table, get a function like the following.
public void createUser(List<User> userList) {
if (userList != null && !userList.isEmpty()) {
SQLiteDatabase db = this.openOrCreateDatabase("Users",MODE_PRIVATE,null);
db.beginTransaction();
try {
for (User user : userList) {
ContentValues values = new ContentValues();
values.put("name", user.getName());
values.put("age", user.getAge());
// Replace on conflict with the unique constraint
db.insertWithOnConflict("users", null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
} catch (Exception e) {
e.printStackTrace();
}
db.setTransactionSuccessful();
db.endTransaction();
}
}
In this way, you do not have to delete any duplicate rows in your table as there will be no duplicate rows either.
However, if your implementation needs duplicate rows and then deleting only the first when you are trying to delete based on some condition then you might consider using the sqlite built-in column ROWID. You get all the rows that matches your condition and save the ROWID of them all. Then you delete the row that matches the ROWID you want to delete.
delete from users where ROWID = 9
Here's the developers documentation of using ROWID.
The approach I would take is to create a table where the duplicates are automatically resolved when data is inserted. Make the "name" field a primary key. Here's the CREATE statement:
CREATE TABLE users (name TEXT PRIMARY KEY ON CONFLICT IGNORE,age INTEGER);
"ON CONFLICT IGNORE" will always keep the first "name" record in the database. If you want to always keep the last record inserted, use "ON CONFLICT REPLACE". For example:
INSERT INTO users VALUES ('Jim','21');
INSERT INTO users VALUES ('Jim','23');
INSERT INTO users VALUES ('Jim','43');
If you use "ON CONFLICT IGNORE" Then "SELECT * FROM users" would produce "Jim|21". If you use "ON CONFLICT REPLACE" Then "SELECT * FROM users" would produce "Jim|43".

sqlite android create unique column that no need to check availability when have to store

I developing news app that store all of news in sqlite database.
It will be a big database during time.
When i get data from API, check database to have every news and if doesn't exist store them to it. it takes 3-10 sec on every time when app run by user ( will take more during days ).
Is there anyway to store my data to database in an asynctask that doesn't freeze my app ? or another efficient way ?
every news has unique id. can i change my id column to unique that i don't have to check every time and store directly to database and database don't save it when it's available ?
for (int i = 0; i < jsonArrayAll.length(); i++)
if (!db.isNewsExist(news.getNews_id()))
db.addNews(news);
public boolean isNewsExist(String news_id) {
boolean exist;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query("news", COLUMNS_NEWS, " news_id = ?",
new String[]{news_id}, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (!cursor.moveToFirst()) {
return false;
}
exist = cursor.getString(1) != null;
cursor.close();
db.close();
return exist;
}
Yes- just put the update code in the doInBackground of an AsyncTask. SQLite can handle being called from multiple threads. As for improvements- don't query and then add. Just try to insert- if the column has a unique constraint that's violated it will throw an exception you can catch and ignore.

Inserting data to SQLite table with constraint failure

Inserting data to SQLite table with constraint failure
I'm trying to insert data into SQLite table on Android. _id is primary key of the table and I am inserting a row using this method:
public void addSomeData(int id, String datetime) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, id);
contentValues.put(KEY_DATETIME, datetime);
mDb.insert(TABLE, null, contentValues);
}
The problem I get is that sometimes primary key constraint is validated and I would like to use something like INSERT IF NOT EXISTS, but preferably something that would work with ContentValues. What are my options? I understand that insertOrThrow() and insertWithOnConflict() methods only return different values, or should I use one of these methods?
Use insertWithOnConflict() with CONFLICT_IGNORE.
Will return ROWID/primary key of new or existing row, -1 on any error.
In my case "constraint failure" happened because of I had some tables which are depended on each other. As for the "insert if not exist", you can query with this id and you check if the cursor's count is bigger than zero. Check the method I'm already using in my app.
public boolean isRowExists(long rowId) {
Cursor cursor = database.query(this.tableName, this.columns, DBSQLiteHelper.COLUMN_ID + " = ? ", new String[] { "" + rowId }, null, null, null);
int numOfRows = cursor.getCount();
cursor.close();
return (numOfRows > 0) ? true : false;
}
to do so you could simply query the db to see if a row with that key exists and insert the new row only if the query returns no data.

Before inserting a record in the database to validate that there is

Before inserting a record in the database to validate that there is, for example I have a table that has two fields, table fields VA with Customer, First, I want to validate the field if there is no customer registration and if there insert
That i want to do in android using Sqlite
String sql = "SELECT * FROM TABLE WHERE id = '" + id + "'";
Cursor data = database.rawQuery(sql, null);
After this check by following code
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
Look at SQLite constraints. This really isn't Android-specific; it's a feature of SQLite.
Try this, it works for me.
String[] args = { myDataToCheck };
c = ourDatabase.query(DATABASE_TABLE, columns,
myColumnToCheck + "=?", args, null, null, null);
if (c.getCount() == 0) {
// doesn't exists
}else{
//exists
}
You have 2 possibilities :
1)make a select to check if there is the same key in database, then insert or update.
2)make directly an update. update will return the number of row updated, if the number is 0, so you can do an insert.

Android + Sqlite : Table creation sql has no effect

I am trying to create a simple android application which creates a database using SQLiteDatabase (not using SQLiteOpenHelper). So the database creation and the table creation sql executes successfully without any issues/exceptions.
Now the issue is when I reopen the same database, the earlier table created does not exist!!
I am checking the existence of the table using the following code :
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+ sqlQueryString +"'", null);
if(cursor!=null) {
if(cursor.getCount() == 0) {
//error handling code here
}
cursor.close();
}
Obviously am ending in the if(cursor.getCount() == 0) condition.
I pulled the db file and also checked with a sqlite viewer on the pc, the table created earlier simply does not exist.
So my question is how do I verify that my create table query has created the table properly?
Adding requested information:
Create table ExampleTable ( ROWID integer primary key autoincrement , FIRSTNAME text , LASTNAME text ) ;
Adding the android code the execute the above query:
db.beginTransaction();
db.execSQL(sqlQueryString);
db.endTransaction();
You need to call db.setTransactionSuccessful() before you end the transaction, or else the operation is assumed to have failed and the transaction is rolled back.
Typical transaction usage is:
db.beginTransaction();
try {
// execute DB queries here
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Credit to njzk2 for first mentioning the solution in a comment.

Categories

Resources