How can I call getContentResolver in android?

我是研究僧i 提交于 2019-12-04 02:10:25

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

You can use like this:

getApplicationContext().getContentResolver() with the proper context.
getActivity().getContentResolver() with the proper context.

Here is how I wound up doing this, for any who may find this thread in the future:

I used sugarynugs' method of creating a class that extends Application, and then added the appropriate registration in the application manifest file. The code for my application class is then:

import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;

public class CoreLib extends Application {
    private static CoreLib me;

    public CoreLib() {
        me = this;
    }

    public static Context Context() {
        return me;
    }

    public static ContentResolver ContentResolver() {
        return me.getContentResolver();
    }
}

Then, to get a ContentResolver in my library class, my function code is such:

public static ArrayList<Group> getGroups(){
    ArrayList<Group> rv = new ArrayList<Group>();

    ContentResolver cr = CoreLib.ContentResolver();
    Cursor c = cr.query(
        Groups.CONTENT_SUMMARY_URI, 
        myProjection, 
        null, 
        null, 
        Groups.TITLE + " ASC"
    );

    while(c.moveToNext()) {
        rv.add(new Group(
            c.getInt(0), 
            c.getString(1), 
            c.getInt(2), 
            c.getInt(3), 
            c.getInt(4))
        );          
    }

    return rv;
}
Nanne

A bit hard without seeing more of how you are coding your library, but I don't see another option then to use the context, and so pass that when calling that class.

A 'random' class does not have the environment to get a contentresolver: you need a context.

Now it's not too strange to actually pass your (activity) context to your class. From http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

On Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context, Activity and Application. It's usually the first one that the developer passes to classes and methods that need a Context

(emphasis mine)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!