java Android:getContext().getContentResolver() 有时会得到 NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32990098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:02:49  来源:igfitidea点击:

Android: getContext().getContentResolver() sometimes gets NullPointerException

javaandroidnullpointerexceptionandroid-contentresolver

提问by Radek O

I want to ask why we get this annotation:

我想问一下为什么我们会得到这个注解:

Method invocation getContext.getContentResolver() may produce NullPointerException

方法调用 getContext.getContentResolver() 可能会产生 NullPointerException

Why is it there and not in other parts of program Fragment/Activity? That approach has been used in tutorial made by Google - here is link for ContentProvider code https://github.com/udacity/Sunshine-Version-2/blob/sunshine_master/app/src/main/java/com/example/android/sunshine/app/data/WeatherProvider.javaeven if you create an aplication with just a blank activity and put that method in a newly created ContentProvider it is there.

为什么它存在而不是在程序片段/活动的其他部分?该方法已在 Google 制作的教程中使用 - 这里是 ContentProvider 代码的链接https://github.com/udacity/Sunshine-Version-2/blob/sunshine_master/app/src/main/java/com/example/android /sunshine/app/data/WeatherProvider.java即使您创建一个只有空白活动的应用程序并将该方法放在新创建的 ContentProvider 中,它也存在。

Should we use getContext().getContentResolver().notifyChange(uri, null);outside ContentProvider getting the uri passed and then after the update/insert/delete is finished notifyChange? or maybe we can fix it somehow?

我们是否应该使用getContext().getContentResolver().notifyChange(uri, null);外部 ContentProvider 获取 uri 传递,然后在更新/插入/删除完成后 notifyChange?或者我们可以以某种方式修复它?

采纳答案by Mate

If you look in the source of ContentProvider (just hold SHIFT and click on the classname in Android Studio) then you will find that the implementation is holding an object of type Context as mContext.

如果您查看 ContentProvider 的源代码(只需按住 SHIFT 并单击 Android Studio 中的类名),那么您会发现该实现将 Context 类型的对象保存为 mContext。

Your solution is just the same, which means if mContext of ContentProvider is null, your reference will also be null. So there is no need for this.

您的解决方案是一样的,这意味着如果 ContentProvider 的 mContext 为空,您的引用也将为空。所以没有必要这样做。

To help you out, this is just a warning of your IDE if make such a construct yourself. But in this case there will always be context, because the ContentProvider is generated by your system. To avoid the error in your IDE just write @SuppressWarnings("ConstantConditions")above your class definition like:

为了帮助您,如果您自己进行这样的构造,这只是对您的 IDE 的警告。但在这种情况下,总会有上下文,因为 ContentProvider 是由您的系统生成的。为避免 IDE 中的错误,只需在类定义上方编写@SuppressWarnings("ConstantConditions"),例如:

...
@SuppressWarnings("ConstantConditions")
public class NoteProvider extends ContentProvider {
...

回答by Manuel B.

If you can make sure that getContext()can never be nullthen you can simply ignore this warning. I think the warning even disappears of you just check for null:

如果您可以确保getContext()永远不会为空,那么您可以简单地忽略此警告。我认为警告甚至会消失,您只需检查 null:

if (getContext() != null) {
    getContext().getContentResolver();
}

You just have to keep in mind the code won't be executed if getContext()is null.

您只需要记住,如果getContext()null ,则不会执行代码。

Cheers

干杯

edit: Be careful with the answer @Shivani Gupta gave you, because you could get different contexts. See: Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

编辑:小心@Shivani Gupta 给你的答案,因为你可以获得不同的上下文。请参阅:getContext() 、 getApplicationContext() 、 getBaseContext() 和“this”之间的区别

回答by Shivani Gupta

Write getApplicationContext().getContentResolver()Hope this will work.

getApplicationContext().getContentResolver()希望这会奏效。

回答by mmrmartin

According to ContentProvider getContext()docs:

根据ContentProvidergetContext()文档

Retrieves the Context this provider is running in. Only available once onCreate() has been called -- this will return null in the constructor.

检索此提供程序正在运行的上下文。仅在调用 onCreate() 后可用 - 这将在构造函数中返回 null。

So the getContext()method does not return nullin insert(), update()or delete(), because onCreate()will be called before these calls.

所以该getContext()方法不会返回nullin insert(), update()or delete(), 因为onCreate()会在这些调用之前被调用。

So it's OK to disable that warning for that line if you use it in such case...

因此,如果您在这种情况下使用该行,则可以禁用该行的警告...

//noinspection ConstantConditions
getContext().getContentResolver().notifyChange(uri, null);

回答by Radek O

Ok it seems I fixed it myself by declaring Contexton the beggining of the class.

好吧,看来我自己通过在课程开始时声明Context来修复它的。

public class NoteProvider extends ContentProvider {
    Context context;

then initializing it in onCreate()

然后在onCreate() 中初始化它

@Override
    public boolean onCreate() {
        mSQLiteOpenHelper = new NoteDbHelper(getContext());
        context = getContext();

        return true;
    }

I think that made sure that I always have Context when I use context.getContentResolver().notifyChange(uri, null);or retCursor.setNotificationUri(context.getContentResolver(), uri);in insert/update/delete/query method- retCursor being returned cursor by mentioned methods.

我认为这确保了我在使用context.getContentResolver().notifyChange(uri, null);时总是有 Context ; retCursor.setNotificationUri(context.getContentResolver(), uri); 在插入/更新/删除/查询方法中 - retCursor 由上述方法返回游标。

I have run the aplication on my phone and did not have issues yet if I will there will probably be an edit for this post.

我已经在我的手机上运行了应用程序并且没有问题,如果我愿意的话,可能会对这篇文章进行编辑。

EDIT:

编辑:

It does not make a difference after all - explanationin answer by @Mate, thank you for that I think I get it now :]

毕竟这并没有什么区别-@Mate 的解释,谢谢你,我想我现在明白了:]

回答by Zain

This usually happens when you call getActivity()or getContext()in a Fragment or DialogFragment to use one of Parent activity methods like getContentResolver()because the compiler is in doubt that these methods may return a null value.

当您调用getActivity()getContext()在 Fragment 或 DialogFragment 中使用 Parent 活动方法之一时,通常会发生这种情况,getContentResolver()因为编译器怀疑这些方法可能返回空值。

To solve this, instead of using getActivity()or getContext(); you can simply use requireActivity()and requireContext()respectively; these methods assure that a non-null value is returned.

要解决此问题,请不要使用getActivity()getContext();你可以简单地分别使用requireActivity()requireContext();这些方法确保返回非空值。

You can take a look on the answer here

你可以看看这里的答案

回答by Lajos Arpad

Whenever you try to use a member or a method of an object, you can have a runtime exception if the object, whose member/method you try to use is null. Let's suppose you want to use a member/method of an object, obj. If you use it like this:

每当您尝试使用对象的成员或方法时,如果您尝试使用其成员/方法的对象为空,则可能会出现运行时异常。假设您想使用对象的成员/方法,obj. 如果你像这样使用它:

if (obj != null) {
    //use members/methods of obj
}

then you prevented the problem. However, you might want to handle it as an exception, like this:

那么你就阻止了这个问题。但是,您可能希望将其作为异常处理,如下所示:

try {
    //use members/methods of obj
} catch (NullPointerException npe) {
    //handle the NullPointerException
}