Android: GetContext().getContentResolver() Sometimes Gets NullPointerException


Answer :

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:

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

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

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

You just have to keep in mind the code won't be executed if getContext() is 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"


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


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?