Search code examples
androidandroid-sqlite

How to prevent duplicate data in android sqlite database?


Iam working on sqlite database in android i want to insert a table like below

                    id procode  proname user
                    1  pro123   mobile   120
                    2  pro123   mobile   121
                    3  pro345   watches  120

in the above table only id is uniq all values are not uniq but i dont want to allow same data for same user it means another user will insert same data now i dont want to insert duplicate while checking data of procode and user means like bwlow

                    id procode  proname user
                    1  pro123   mobile   120
                    2  pro123   mobile   121
                    3  pro123    mobile   120 

in the above table 3 is duplicate data


Solution

  • When you insert new row you have the new USER.

    So before inserting data into your DB.

    Check whether already same USER data exists or not.

    Below is SQLITE Query hint for the same

    Cursor c=db.rawQuery("SELECT * FROM user WHERE user="YOUR_VALUE", null);
    if(c.moveToFirst())
    {
     showMessage("Error", "Record exist");
    }
    else
    {
     // Inserting record
    }