I have a user interface in my Android app that allows users to choose from sqlite database what they want to see.
For example user can choose to see male contacts, but the user can also choose "doesn't matter" to see both male and female.I have written the following code to get contacts from database.
public List<Contact> get_contact(String name, String age, String gender){
List<Contact> contacts=new ArrayList<>();
DatabaseHelper dbHelper=new DatabaseHelper(context);
SQLiteDatabase db=dbHelper.getReadableDatabase();
String sql="SELECT * FROM Tablename WHERE name = ? AND" +
" age = ? AND" +
" gender = ?";
String[] selectionArgs = new String[]{name, age, gender};
Cursor cursor=db.rawQuery(sql,selectionArgs);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setName(cursor.getString(cursor.getColumnIndex("name")));
contact.setAge(cursor.getString(cursor.getColumnIndex("age")));
contact.setGender(cursor.getString(cursor.getColumnIndex("gender")));
contacts.add(contact);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contacts;
}
but the problem is when user chooses "doesn't matter", for example, for age or gender, I don't know how to do that. I used this code to get all contacts with age 20 but it didn't work.
List<Contact> contacts = get_contact(null,"20",null);
And i don't want to write a different query for each state, because there is too many states and in fact I have 5 arguments instead of 3, for get_contact() method.
Here is the error I get.
java.lang.IllegalArgumentException: the bind value at index 3 is null