Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call getContentResolver in android?

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.

like image 505
eidylon Avatar asked Feb 04 '11 06:02

eidylon


People also ask

What is getContentResolver in Android?

The getContentResolver() method is also used when you query a Contact , using a Cursor object. I have used getContentResolver() to query the Android phone Contacts app, looking for contact info from a person's phone number, to include in my app.

How do I use getContentResolver adapter?

In order to call getContentResolver() you need a Context object of your activity, you have to ways to do this when using the BaseAdapter class. Then just call context. getContentResolver() .

What does ContentResolver query () return?

The ContentResolver. query() client method always returns a Cursor. This cursor contains the column specified by the query projection. The cursor object provides read access to rows and columns.


2 Answers

Have each library function call pass in a ContentResolver... Or extend Application to keep hold of a context and access it statically.

like image 99
techiServices Avatar answered Oct 10 '22 23:10

techiServices


You can use like this:

getApplicationContext().getContentResolver() with the proper context.
getActivity().getContentResolver() with the proper context.
like image 39
codercat Avatar answered Oct 10 '22 23:10

codercat