I have 3 tables in my sqlite database. They are games, movies, and books. I want to create a new item in the table only if there's another with the same name doesn't exist. This is the current code I have. When I want to check for duplicate entry before adding a new item in the table, the app crashes.
// Adds an item to our database
public void createItem(Item item, String table) {
SQLiteDatabase db = this.getWritableDatabase(); //reference the database
ContentValues values = new ContentValues();
values.put("name", item.getName());
values.put("creator", item.getCreator());
values.put("genre", item.getGenre());
db.insert(table, null, values);
db.close();
}
The current method I was using to check if one already existed is:
// Checks if an item exists before we add it to the database more than once
private boolean doesExist(String TableName, String fieldValue) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " +TableName+"WHERE NAME = " + fieldValue +"",null);
if (cursor == null) {
db.close();
return false;
} else {
return true;
}
}
And here is my code for the button clicked to add the record:
public void clickAdd(View view) {
ImageView image = (ImageView) view;
String table = TableAssistant.getTableName(image);
Database db = new Database(getApplicationContext());
Item item = new Item();
item.setName(txtName.getText().toString());
item.setGenre(txtGenre.getText().toString());
item.setCreator(txtCreator.getText().toString());
db.createItem(item, table);
}
Any help to get this to validate without crashing would be appreciated.