I’m developing an Android application that makes a Query using Activity.managedQuery(), which takes a String for the selection argument. The argument is the WHERE clause of a SQL statement, but excluding the WHERE keyword.
My application uses the first and last names of people who might be in the user’s address book. However, some people have a name which contains a single quote character. For example, John O'Reilly. This causes a SQLiteException because the single quote terminated the string and it doesn’t know how to handle Reilly.
I tried doing a simple:
name = name.replace("'", "\\'");
But this didn’t work.
The full exception looks like this:
android.database.sqlite.SQLiteException: near "Reilly": syntax error: , while compiling:
SELECT raw_contact_id, display_name FROM view_data_restricted data WHERE (1) AND
(in_visible_group = '1' AND display_name ='John O\'Reilly') ORDER BY display_name
COLLATE LOCALIZED ASC
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
at android.content.ContentResolver.query(ContentResolver.java:262)
at android.app.Activity.managedQuery(Activity.java:1550)
at org.jonescb.myApp.MyClass.queryFriends(MyClass.java:68)
This is my code:
fname = fname.replace("'", "\\'");
Uri contacts = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Data.RAW_CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP +
" = '1' AND " + ContactsContract.Contacts.DISPLAY_NAME +
" ='" + fname + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME +
" COLLATE LOCALIZED ASC";
Cursor cursor = activity.managedQuery(
contacts,
projection,
selection,
null,
sortOrder
);
use selectionArguments