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

后端 未结 7 1692
北恋
北恋 2021-02-20 02:05

I want to ask why we get this annotation:

Method invocation getContext.getContentResolver() may produce NullPointerException

Why i

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 02:48

    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"

提交回复
热议问题