views:

25

answers:

1

I'm trying to query the Contacts content provider outside an Activity. But managedQuery is a method of Activity. Is there any other class/method that I can use instead of managedQuery?

Here's my code:

class MyActivity extends Activity {

  private Cursor getContacts() {
 Uri uri = ContactsContract.Contacts.CONTENT_URI;
 String[] projection = new String[] { ContactsContract.Contacts._ID,
   ContactsContract.Contacts.DISPLAY_NAME,
   ContactsContract.Contacts.HAS_PHONE_NUMBER };
 String where = null;
 String[] whereArgs = null;
 String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
   + " COLLATE LOCALIZED ASC";

 return context.managedQuery(uri, projection, where, whereArgs, sortOrder);
  } 
}
A: 

Use ContentResolver.query() instead.

(call Context.getContentResolver() to get an instance of ContentResolver. You will need a Context anyway, but it does not have to be an Acitivity)

Activity.managedQuery() takes care of dealing with the Activity lifecycle with respect to the Cursor. ContentResolver.query() does not do that, so you will have to make sure to close and requery etc. the cursor yourself.

Thorstenvv
This would have to mean that my class still needs to inherit from Context right?
javauser
No, but you need to get a valid context from somewhere (could as well be a service). What is the usage scenario you would want to run the query in?
Thorstenvv