android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed Couldnot figure out what the error says

Tags: , , ,



I have got stuck in the above-mentioned error message in Android Studio. My Database is a simple one 1st column: Name TEXT PRIMARY KEY 2nd column: Price TEXT

I have already gone through the answers to the same question in StackOverflow but couldn’t resolve the error.

I am quoting my DataBaseHelper class and insertActivity here:

    private static final String DATABASE_NAME = "ItemDatabase";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "Items";
    private static final String COLUMN_NAME = "Name";
    private static final String COLUMN_PRICE = "Price";

    DataBaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + "(" + COLUMN_NAME + " TEXT NOT NULL PRIMARY KEY, " + COLUMN_PRICE + " TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        String sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
        sqLiteDatabase.execSQL(sql);
        onCreate(sqLiteDatabase);
    }

    boolean addItem(String itemName, String itemPrice) {

            ContentValues contentValues = new ContentValues();
            contentValues.put(COLUMN_NAME, itemName);
            contentValues.put(COLUMN_PRICE, itemPrice);
            SQLiteDatabase db = this.getWritableDatabase();
            boolean b = db.insert(TABLE_NAME, null, contentValues) != -1;
            db.close();
            return b;

    }

    Cursor getPrice(String itemName) {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.rawQuery(" SELECT Price FROM  Items WHERE Name= ? ", new String[]{itemName});
    }

    Cursor updatePrice(String itemName, String itemPrice)
    {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.rawQuery(" UPDATE Items SET Price= ? WHERE Name= ? ", new String[]{itemPrice,itemName});
    }

    public List<String> getName(){
        List<String> list = new ArrayList<String>();

        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);


        if (cursor.moveToFirst()) {
            do {
                list.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();

        return list;
    }
}
public class insertActivity extends AppCompatActivity {

   EditText itemName,itemPrice;
   Button buttonInsert;
   boolean b;


   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_insert);

       itemName= findViewById(R.id.itemName);
       itemPrice= findViewById(R.id.itemPrice);
       buttonInsert=findViewById(R.id.buttonInsert);

       final String Name=itemName.getText().toString();
       final String Price=itemPrice.getText().toString();



       final DataBaseHelper dataBaseHelper =new DataBaseHelper(getApplicationContext());

       buttonInsert.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               try {
                   b = dataBaseHelper.addItem(Name,Price);
               }catch (Exception e)
               {
                   e.printStackTrace();
               }

              if( b )
               {
                   Toast.makeText(getApplicationContext(),"Item Inserted Successfully ",Toast.LENGTH_SHORT).show();
               }
               else
                   Toast.makeText(getApplicationContext(),"Item Insertion Failed ",Toast.LENGTH_SHORT).show();
           }
       });




   }
}

error:

W/System.err:     at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:746)
W/System.err:     at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
        at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
        at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1770)
        at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
        at com.anirbit.anirbitadak.nirman.DataBaseHelper.addItem(DataBaseHelper.java:45)
W/System.err:     at com.anirbit.anirbitadak.nirman.insertActivity$1.onClick(insertActivity.java:39)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25881)
W/System.err:     at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err:     at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6649)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)```

Answer

These lines:

final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();

assign to the variables Name and Price the text of the EditTexts itemName and itemPrice when the insertActivity loads (maybe they are just empty strings) and they are never changed.
So when you click the button the listener by calling dataBaseHelper.addItem(Name,Price) tries to insert the same values in the table and this results to the error you get because since the column Name is the Primary Key of the table it must be unique.

What you must do is move these lines inside the listener:

buttonInsert.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    final String Name=itemName.getText().toString();
    final String Price=itemPrice.getText().toString();

    try {
    ................................................
}

so when you click the button the correct values are retrieved from the EditTexts and then inserted in the table.



Source: stackoverflow