I want to enter name and phone number from two edit text.i use two buttons to save and show it in emulator using list view.After entering name and when i click save button
Put UNIQUE
in your table field definition an then use insertOrThrow
. If you insert the same, insertOrThrow
will cause an exception, you can intercept it.
I would start with changing your table definition by adding the NOT NULL and UNIQUE constraints.
db.execSQL("CREATE TABLE "+tbname+"("+Key_id+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Key_name+" TEXT NOT NULL UNIQUE,"+Key_mobile+" TEXT)");
Then you have a choice of methods to use for your insert. You can use:
insertOrThrow
will return the id of your new record, or -1 on an error (and a constraint failure of not having a unique name would be an error).
insertWithOnConflict
will return the id of the new record OR the primary key of the existing row if the input param 'conflictAlgorithm' = CONFLICT_IGNORE OR -1 if any error.
Personally, I would use insertWithOnConflict
with the CONFLICT_IGNORE flag set. That way you can get the row id back for the duplicate record (as well as not letting the duplicate get entered).