0

I have a button, when user clicks it it passes some value and im adding this value with cv.put("name", name), how can i avoid adding duplicates?

3
  • check where not exist command on sql it might help. or you can simply inner join your own table and check if it does exist or not. Commented Apr 1, 2017 at 11:26
  • stackoverflow.com/a/26326817/3998402 solves your problem Commented Apr 1, 2017 at 11:27
  • On SO, either accept an answer, or write your own answer. Commented Apr 1, 2017 at 18:36

3 Answers 3

1

1- Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.

2-When inserting, add a value to this constrained column via ContentValues. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.

ContentValues Val = new ContentValues();
Val.put("IDD", id); 
Val.put("Category", cat);
long rows=db.insertWithOnConflict(TABLE_CATEGER, null,  Val,SQLiteDatabase.CONFLICT_REPLACE);
System.out.print(rows);
db.close(); 
Log.d(TAG,""+ rows);

Gordon Linoff answer shows you how to make some columns UNIQUE

Sign up to request clarification or add additional context in comments.

Comments

0

it`s better to do it in your database structure in your

 SQLiteOpenHelper

 db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
                + MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
                + MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
                + MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT IGNORE"+");";

this will ignore any conflict in your Field

or use

 db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
                + MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
                + MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
                + MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT REPLACE"+");";

to replace when conflict in Field

Comments

0

I you have a table t and you do not want duplicate values of name, then the best method is to have the database maintain the integrity of the data.

SQL offers unique indexes/constraints just for this purpose. For instance, you can create a unique index on the data:

create unique index unq_t_name on t(name);

Any attempt to create a duplicate name value in t (whether by insert or update) will generate an error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.