如何在没有活动的类中使用getContentResolver? [英] how use getContentResolver in a class without activity?
问题描述
我的课看起来像这样:
public class sendInformation{
public void test() throws Exception {
Uri uri = SuspiciousActivityTable.CONTENT_URI;
getContentResolver().update(uri, values2, where,new String[]{"Null"});
}
}
}
但是它说 getContentResolver()
不存在,我知道我需要一个Context或Activity来完成这项工作,但是如何在这里获取正确的Context?
but it say getContentResolver()
doesn't exist, I know I need a Context or Activity to make this work but how do I get the correct Context here?
推荐答案
You will need to pass off a Context, even the ContentResolver
class needs a valid context to be instantiated.
最简单的方法是将该方法作为参数:
Simplest way is as an argument to the method:
public void test(Context context) throws Exception {
Uri uri = SuspiciousActivityTable.CONTENT_URI;
context.getContentResolver().update(uri, values2, where,new String[]{"Null"});
}
然后调用:(假设包含 test
的类被实例化 ,并且您的Activity的名称为 MyActivity
<-替换为您正在调用的活动
名称 test()
from )
And to call: (assuming that the class that contains test
is instantiated and your Activity's name is MyActivity
<- Replace with the Activity
name you're calling test()
from)
try{
sendInformationInstanceVariable.test (MyActivity.this);
}
catch (Exception e)
{
e.printStackTrace();
}
MyActivity.this
可以简化为 this
,如果您不是从以下位置调用 test()
在一个匿名内部类中.
MyActivity.this
can be shortened to just this
if you're not calling test()
from inside an anonymous inner class.
此外,如果您的类确实没有充分的理由要实例化,请考虑将 test()
设为 static
方法,如下所示:
Also, if your class really doesn't have a good reason to be instantiated, consider making test()
a static
method, like this:
public static void test(Context context) throws Exception {
Uri uri = SuspiciousActivityTable.CONTENT_URI;
context.getContentResolver().update(uri, values2, where,new String[]{"Null"});
}
然后从您的 Activity
中调用该方法,而无需实例:
Then from your Activity
, you call this method without needing an instance:
try{
sendInformation.test (MyActivity.this);
}
catch (Exception e)
{
e.printStackTrace();
}
最后,抛出 Exception
是不好的做法,不要没有充分的理由就不要这样做,如果确实有充分的理由,请尽可能具体.
Lastly, throwing Exception
is bad practice, do don't do it without good reason and if you do have a good reason, be as specific as possible.
这篇关于如何在没有活动的类中使用getContentResolver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!