Check if value exist in DB with Boolean in Java

Viewed 329

What I want to do is check if there's any data inside the profilePicture column on 'profiles' table, if there's no data, the getCount will return 0 and shall return false. How do I make the query to only fetch the data in profilePicture column to see if it's null or not for the user id.

public Boolean checkProfilePicture(String user_id){
        SQLiteDatabase MyDB = this.getReadableDatabase();

        Cursor cursor = MyDB.rawQuery("Select * from profiles where ID = ? and profilePicture = NULL", new String[] {user_id});
        System.out.println(cursor.getCount());

        if (cursor.getCount() > 0)
            return true;
        else
            return false;
    }
1 Answers

Your query should return only 1 column which is a boolean value in the form of 1 (true) or 0 (false) and for this you must use an expression like:

profilePicture IS NOT NULL

You must compare to NULL with the operator IS or IS NOT and not with = or <> or !=:

public boolean checkProfilePicture(String user_id){
    SQLiteDatabase MyDB = this.getReadableDatabase();
    Cursor cursor = MyDB.rawQuery("SELECT profilePicture IS NOT NULL FROM profiles WHERE ID = ?", new String[] {user_id});
    boolean result = cursor.moveToFirst();
    if (result) result = (cursor.getInt(0) == 1) ;
    cursor.close();
    MyDB.close();
    return result;
}
Related