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

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

问题描述

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

I want to ask why we get this annotation:


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

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.

我们应该使用 getContext()。getContentResolver()。notifyChange(uri,null); 在ContentProvider之外获取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的来源(只需按住SHIFT并单击类名)在Android Studio中)你会发现实现持有一个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.

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

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天全站免登陆