Android:getContext().getContentResolver() 有时会得到 NullPointerException [英] Android: getContext().getContentResolver() sometimes gets NullPointerException

查看:70
本文介绍了Android:getContext().getContentResolver() 有时会得到 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to ask why we get this annotation:

方法调用 getContext.getContentResolver() 可能会产生空指针异常

Method invocation getContext.getContentResolver() may produce NullPointerException

为什么它存在而不是在程序片段/活动的其他部分?该方法已在 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 中,它就在那里.

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.java even if you create an aplication with just a blank activity and put that method in a newly created ContentProvider it is there.

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

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?

推荐答案

如果你查看 ContentProvider 的源代码(在 Android Studio 中按住 SHIFT 并点击类名)然后你会发现该实现是持有一个对象将 Context 输入为 mContext.

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 的 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.

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

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:

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

这篇关于Android:getContext().getContentResolver() 有时会得到 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆