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);
  } 
}
javauser
  • 215
  • 1
  • 3
  • 7

1 Answers1

8

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
  • 5,376
  • 1
  • 34
  • 28
  • This would have to mean that my class still needs to inherit from Context right? – javauser Oct 10 '10 at 00:10
  • 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 Oct 11 '10 at 15:58
  • How do I get a valid context from "wherever"? For example from a static function defined in a Utils class – matteo Feb 16 '12 at 21:23
  • In a static context, you will need to either add a context parameter for the method, or access the application's context in a static way. Derive your own Application class from android.app.Application and register it in the Application Manifest, so it will be instantiated by the framework when loading the application. In your Application class' constructor you can then set a static member referring to the instance so that you can access it from your static Utils methods. – Thorstenvv Feb 20 '12 at 14:28