I'm writing a library class to encapsulate some of my logic in my first Android app. One of the functions which I want to encapsulate is a function which queries the address book. As such, it needs a ContentResolver
. I'm trying to figure out how to keep the library functions black-boxed... that is, to avoid having each Activity
pass in its own context to get a ContentResolver
.
Problem is I cannot for the life of me figure out how to get a ContentResolver
from within my library function. I can't find an import that contains getContentResolver
. Googling said to use getContext
to get a Context
on which to call getContentResolver
, but I can't find an import containing getContext
either. Next posts said to use getSystemService
to get an object to call getContext
. BUT - I can't find any import containing getSystemService
either!
So I'm stuck wondering, how can I get a ContentResolver within an encapsulated library function, or am I pretty much stuck having every calling Activity
pass in a reference to its own context?
My code is something basically like this:
public final class MyLibrary {
private MyLibrary() { }
// take MyGroupItem as a class representing a projection
// containing information from the address book groups
public static ArrayList<MyGroupItem> getGroups() {
// do work here that would access the contacts
// thus requiring the ContentResolver
}
}
getGroups is the method where I was looking to avoid having to pass in a Context
or ContentResolver
if I could, as I was hoping to have it cleanly black-boxed.
You can use like this:
getApplicationContext().getContentResolver() with the proper context.
getActivity().getContentResolver() with the proper context.