androidandroid-contentproviderandroid-contentresolverandroid-query

Meaning and Purpose of " = '1' " in ContentResolver Query


String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER " + " = '1''";
String[] selectionArgs = String.valueOf(1);

Why do we put " = '1' " in the Selecion Query ?

and Also the Reason for String.valueOf(1);


Solution

  • You probably meant this:

    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?";
    String[] selectionArgs = new String[]{String.valueOf(1)};
    

    or this

    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?";
    String[] selectionArgs = new String[]{"1"};
    

    or this

    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
    String[] selectionArgs = null;
    

    or just this

    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = 1";
    String[] selectionArgs = null;
    

    All four selections have the same results: Contacts that have a phone number.

    SQLite (the database type that's used on Android) doesn't support Booleans (see Datatypes in SQLite Version 3), true and false are usually stored as integers 1 and 0. So, to check if a boolean field is true you check if it has the value 1.

    Code snippets #1 and #2 use a prepared statement which contains a parameter or placeholder that's replaced with the first value of the selectionArgs array (since it's the first parameter in the query). This is a technique to protect against SQL injection and it often makes your queries better readable. selectionArgs has to be an array of String values, so the integer value 1 in snippet #1 needs to be converted to a String first (using String.valueOf(int) actually only makes sense if you pass a variable rather than a constant number).

    If you don't use any variables in your select statement you can just insert all values into the statement not using placeholders and selectionArgs as in code snippets #3 and #4. Since SQLite is dynamically typed it doesn't matter if you check for equality to 1 or '1', the SQL interpreter will get it right either way.