0

I am trying to make a query to sqlite android to see for example how many users of a given username exist in a table. This is my function. I must specify that "getContentResolver() != null" and so is variable name.

private int findSelectedUser(String name) {
        int count = 0;

        try {
            String[] whereArgs = new String[] {name};
            String[] PROJECTION = new String[] { MyProvider.SETTINGS_USERNAME };
            Cursor c = getContentResolver().query(MyProvider.SETTINGS_URI,
                    PROJECTION, MyProvider.SETTINGS_USERNAME , whereArgs, null);
            if (c != null) {
                count = c.getCount();
                c.close();
            }
        } catch (NullPointerException e) {

        }
        System.out.println("Found something? " + count);
        return count;
    }

And after running i receive the error from the subject...and don't get it. In my where clause i have one column, in my where arguments one value. Please help me make some sence of this, Thank you.

0

1 Answer 1

8

I guess that works:

String[] whereArgs = new String[] {name};
String[] PROJECTION = new String[] { MyProvider.SETTINGS_USERNAME };
Cursor c = getContentResolver().query(MyProvider.SETTINGS_URI,
        PROJECTION, MyProvider.SETTINGS_USERNAME + "=?" , whereArgs, null);
if (c != null) {
    count = c.getCount();
    c.close();
}

If you want to use whereArgs you have to have the same amount of ? in the where as you have items whereArgs

whereArgs will replace the ? in the final database query

String where = "name = ? OR name = ?";
String[] whereArgs = new String[] {
    "Peter",
    "Jim"
};

that results in name = 'Peter' OR name = 'Jim' for the query.

Btw: don't catch(NullPointerException e) - make your code safe so they can't happen

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.