2

I need to search the DISPLAY_NAME field 1st and last name and have tried this code:

ContentResolver cr = getContentResolver(); 
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,     ContactsContract.Contacts.DISPLAY_NAME + " like %?%", new String[]{ results.get(0) }, null); 

if (cur.getCount() > 0) {

I get error in log cat from the %'s in the cursor line. Any advise would be appreciated. ??

David
  • 99
  • 1
  • 9

3 Answers3

2

ContentResolver.query() puts ' ' around substitute for question mark, so what you need is

Cursor cur = cr.query(
     ContactsContract.Contacts.CONTENT_URI, 
     null,
     ContactsContract.Contacts.DISPLAY_NAME + " like ?", 
     new String[]{ "%" + results.get(0) + "%"}, 
     null); 
Vladimir
  • 9,683
  • 6
  • 36
  • 57
  • this works, but pulls up all the available contacts for keyword. It starts calling 1st contacts, I hit end call..then it auto starts to dial 2nd #, then i hit end... and so on.. I thought the .get(0) would take care of that. Any idea please? – David Jan 12 '12 at 13:54
  • i can't really tell out of context, but in boundaries of this question you can use little hack to limit query result to one row: add `ContactsContract.Contacts.DISPLAY_NAME ASC LIMIT 1` instead of `null` for you `cr.query()`. this will result in query like **SELECT** ... **ORDER BY** _display_name ASC LIMIT 1_ – Vladimir Jan 12 '12 at 15:00
  • how can i post results to a list for user to pick from? ..can we continue this in chat? Thank u! – David Jan 12 '12 at 15:06
  • take a look at android documentation for [ListView](http://developer.android.com/reference/android/widget/ListView.html) and [CursorAdapter](http://developer.android.com/reference/android/widget/CursorAdapter.html) , and if you run into trouble you can post a separate question – Vladimir Jan 12 '12 at 15:10
0

Try to put single quotes "'%?%'"

How to perform an SQLite query within an Android application?

hope this helps. tyvm.

If you want to use ? as a your parameter you might want to create a dynamic built SQL string beforehand and run it later.

Community
  • 1
  • 1
Sergey Benner
  • 4,421
  • 2
  • 22
  • 29
0

According to what i can gather from:

http://www.techonthenet.com/sql/like.php

it looks like you have to encapsulate your like part like so:

"like '%?%'"
JoxTraex
  • 13,423
  • 6
  • 32
  • 45