lundi 6 juillet 2015

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?

Aucun commentaire:

Enregistrer un commentaire