I created two tables in my database. In both tables, I insert the value at the same time, now what I want to do is that I want to insert the record into the second table, but the condition is that if these are two identical records, then I want to insert only one record, not a duplicate value. In the second table there are two fields: id , and the second category , when the user inserts two identical categories this time I want to insert only one record, below is my code that does not work properly, Inserts all records that take a duplicate value.
public long InsertCat(String idd, String cat)
{
try
{
SQLiteDatabase db;
long rows = 0;
db = this.getWritableDatabase();
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_CATEGER + " WHERE Category='"+cat+"'",null);
while(c.moveToNext())
{
if(c.getString(0).equals(cat))
{
flag=true;
}
}
if(flag==true)
{
rows=db.update(TABLE_CATEGER, Val, "Category='"+cat+"'" , null);
System.out.print(rows);
db.close();
}
if(flag==false)
{
rows = db.insert(TABLE_CATEGER, null, Val);
System.out.print(rows);
db.close();
}
return rows;
} catch (Exception e) {
return -1;
}
}