How can I call getContentResolver in android?
我正在编写一个库类以在我的第一个Android应用程序中封装一些逻辑。我要封装的功能之一是查询通讯录的功能。因此,它需要一个
问题是我一生无法解决如何从库函数中获取
因此,我很想知道,如何在封装的库函数中获取ContentResolver,还是让每个调用
我的代码基本上是这样的:
1 2 3 4 5 6 7 8 9 10 | 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是我希望避免必须通过
您可以这样使用:
1 2 | getApplicationContext().getContentResolver() with the proper context. getActivity().getContentResolver() with the proper context. |
使每个库函数调用都通过
对于将来可能会发现此线程的任何人,这是我最后的想法:
我使用sugarynugs的方法创建了一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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(); } } |
然后,要在我的库类中获取ContentResolver,我的函数代码应为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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; } |
有点困难,没有看到更多有关如何编写库的代码,但是我看不到使用上下文的另一种选择,因此在调用该类时传递了它。
"随机"类没有获取contentresolver的环境:您需要上下文。
现在将您的(活动)上下文实际传递给您的类并不奇怪。来自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
(强调我的)