-1
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);

Tushar Sharma
  • 192
  • 1
  • 15
  • That doesn't look like valid Java code. Also please add more context to our code snippets. `selection` and `selectionArgs` don't seem to belong together. – Marten Apr 11 '16 at 20:25

1 Answers1

1

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.

Marten
  • 3,802
  • 1
  • 17
  • 26
  • It was a Dumb Question i just posted it without Studying the details of the query() method. Thanks though for answering. – Tushar Sharma Apr 11 '16 at 21:39