Search code examples
javaandroidsqladmin

Incompatible data type in parameterized query? (Java)


I'm currently working on an application that uses a SQL database to store the account information of users (username, password, etc.). In the app, there are both regular users and admin users. I'm also using a parameterized query, something that's still quite new to me, in order to check a user's admin status. The onCreate() method for the users table (which is what I'm using to store the user information) is shown below.

public void onCreate(SQLiteDatabase myDB) {
    myDB.execSQL("create Table users(username Text primary key, password Text, email Text, 
    phone Text, admin Integer, userID Text)");
}

So, as you can see, the admin column stores an integer. In the context of my application, 0 denotes a non-admin user and 1 denotes an admin user. I'm using a parameterized query to check if a certain user exists in the users table and also has admin status (if the integer in their admin column is 1). The code for checking if the user is an admin is shown below.

// returns true if user is an admin, false if non-admin
public boolean checkAdmin(String username) {
    SQLiteDatabase myDB = this.getWritableDatabase();
    Cursor cursor = myDB.rawQuery("select * from users where username = ? and admin = ?", new String[] {username,1});
    if (cursor.getCount()>0) // cursor > 0 if user exists in the database and has admin status
        return true;
    else
        return false;
}

Essentially the SQL query is just select * from users where username = username and admin = 1, but the problem I run into is in new String[] {username,1}. The "1" parameter is underlined red and Android Studio tells me that the required type is String. Again, I'm still new to parameterized queries and I'm confused as to why I get such an error when the admin data type is int.


Solution

  • You are declaring an array of String new String[] try adding the 1 as a string.

    Cursor cursor = myDB.rawQuery("select * from users where username = ? and admin = ?", new String[] {username,"1"});