Sumeet
Sumeet

Reputation: 8292

Avoid duplicate entries in SQLite

I am writing a small application in android to store basic details about person using SQLite.

I insert data using this function

public void insertData(String user,String p_no,SQLiteDatabase db)
    {         
            ContentValues cv = new ContentValues();
            cv.put(NAME, user);
            cv.put(PHONE, p_no);
            db.insert("MYTABLE", null, cv);
    }

The above function allows duplicate names to be stored.

So I wrote a function that will first check whether a name exits and then enter.

public void insertData(String user,String p_no,SQLiteDatabase db)
    {
        Cursor resultSet=db.rawQuery("select NAME from MYTABLE where NAME = '"+user+"'",null);
        if(resultSet==null)
        {
            ContentValues cv = new ContentValues();
            cv.put(NAME, user);
            cv.put(PHONE, p_no);
            db.insert("MYTABLE", null, cv);
        }
        else Toast.makeText(context,user+" already exists",Toast.LENGTH_SHORT).show();
    }

But the problem is now toast comes up every time I insert meaning even if the row is unique it is not inserted.

Why resultSet is not null even when there is no such row?

Upvotes: 0

Views: 2703

Answers (3)

Kamal
Kamal

Reputation: 1415

Check

if (resultset.getCount() == 0) 

Also, create Name as unique key to avoid duplicates. Instead of checking it everytime.

Upvotes: 0

Darpan
Darpan

Reputation: 5795

It is because RawQuery never returns null cursor, and that's what your checking criteria is, so it is failing always, and trying to add new value in DB. I am not able to find the documentation where I learned it, but I will update as soon as possible.

You can check if you have values in cursor using -

if(cursor.moveToFirst())

Upvotes: 3

Blackbelt
Blackbelt

Reputation: 157447

because it is possible to have an empty cursor. Change your check like

if(cursor.getCount() == 0)

this way, if the cursor is not null, you check if it contains something too.

Probably this is not the best way to handle duplicates, in my opinion. You should mark your column as unique, and use insertWithConflict, to decide what to do in case you have already an entry with that value

Upvotes: 1

Related Questions