Radek O Radek O - 1 year ago 153
Android Question

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

I want to ask why we get this annotation:

Method invocation getContext.getContentResolver() may produce

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.

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?

Answer Source

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.

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.

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:

public class NoteProvider extends ContentProvider {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download