'How to check if an item is in a database before trying to add it
I have an android app that is adding to and updating a database. The student ID number is the primary key. I'm trying to have the app display a message when the user attempts to add a duplicate. This is my latest attempt; it's triggering the catch clause.
In my main activity, I have this conditional statement:
if (!dbHandler.checkStudentID(studentID)){
Toast.makeText(MainActivity.this, "Student ID is a Duplicate",
Toast.LENGTH_SHORT).show();
}
dbHandler.addNewStudent(studentID, firstName, lastName, grade);
In my handler the method is this:
public boolean checkStudentID (String studentID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor checkID = db.rawQuery("SELECT student_id FROM " + TABLE_NAME +
" where student_id=?", new String[]{studentID});
String x = checkID.getString(0);
checkID.close();
return x.isEmpty();
}
Logcat isn't showing any issues and there aren't any syntax problems shown, so I'm at a loss as to what's not correct.
Solution 1:[1]
The problem is if the studentID could not be found, String x = checkID.getString(0) contains null. And with that, calling x.isEmpty() will throw a NullPointerException. So you should intercept that by:
public static boolean checkStudentID (String studentID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor checkID = db.rawQuery("SELECT student_id FROM " + TABLE_NAME +
" where student_id=?", new String[]{studentID});
String x = checkID.getString(0);
checkID.close();
if (x == null || x.isEmpty()) {
return false;
}
else {
return true;
}
}
I think you could even leave x.isEmpty() out altogether.
If the Toast.makeText().show() doesn't terminate the program, you should better wrap that addNewStudent part in an else-case. Otherwise, it will still be executed!
if (!dbHandler.checkStudentID(studentID)){
Toast.makeText(MainActivity.this, "Student ID is a Duplicate",
Toast.LENGTH_SHORT).show();
}
else{
dbHandler.addNewStudent(studentID, firstName, lastName, grade);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
