TenTen Peter TenTen Peter - 1 month ago 7
Android Question

Check if value exist in SQLite. If it exists, alert the user that the value exists

I've created a table in

SQLite
, and I want to check if the value exist before the user can add that value to the table. Please, check my code below:

//check if value exists

Cursor checkIfExist = shoppingListDB.rawQuery("SELECT * FROM "+ selected_spinner + " WHERE " + "ITEM_NAME = " + "'" + add_tems + "'", null);

if (checkIfExist == null) {
String insert_data="INSERT INTO " + selected_spinner + " (ITEM_NAME,SHOP_LIST,NUMB_ITEMS) VALUES " + "('" + add_tems + "'," + "'" + add_shop + "'," + "'" + add_quantity + "'" + ")";
shoppingListDB.execSQL(insert_data);
} else
Toast.makeText(getBaseContext(), " " + add_tems + " Exists", Toast.LENGTH_LONG).show();

Answer

The else clause is executed because the Cursor object will never be null. The rawQuery() always returns a Cursor object. So you need to test if the sql query affected one or more rows or not:

if(checkIfExist.moveToFirst()){
    //value exist
}else{
    //value does not exist
}

moveToFirst() returns false if the Cursor is empty(doc)