1

I am trying to build a method to determine if a user exists in an Android sqlite database before inserting, I have tried to build this method to return the number of rows, however If I try a search for like matches like this

    String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
            USER_ID };
    Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
            + " LIKE '" + screenName + "%'", null, null, null, null);
    c.moveToFirst();
    Integer count= c.getCount();
    c.close();

    return count;

I get the number of rows returned no problem however the minute I look for an exact match like this

String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
            USER_ID };
    Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
            + " = '" + screenName + "'", null, null, null, null);
    c.moveToFirst();
    Integer count= c.getCount();
    c.close();

    return count;

I get 0 rows every time no matter if it matches or not, Im not sure if theres something wrong with my SQL or maybe im using the wrong arguments to make the statement, any help would go a long way thanks

3
  • Why are you using LIKE? Your LIKE query is looking for a prefix match, not a full match like = will look for. You might be better off adding an appropriate unique constraint on the screen name column and trapping the exception. Commented Jun 1, 2013 at 19:19
  • I was using the LIKE as an example of something I got that worked, what I need is the number of rows returned for an exact match, however I cant seem to get that to work in the second example Commented Jun 1, 2013 at 19:25
  • Do you have that screen name in your database? Does the screen name inside the database and the one you're querying on only differ in case? Commented Jun 1, 2013 at 19:30

1 Answer 1

2

Try this code it might work

Using Raw Query

Cursor mCount= db.rawQuery("select count(*) from "+ DATABASE_TABLE +" where "+SCREEN_NAME+"='" + SCREEN_NAME + "'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();

Or using the same code but differently

db.query(DATABASE_TABLE , columns, SCREEN_NAME=?, new String[] { SCREEN_NAME}, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
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.