【问题标题】:My Context gives me a null reference pointer [duplicate]我的上下文给了我一个空引用指针[重复]
【发布时间】:2016-12-17 19:35:46
【问题描述】:
我试图在我的主 Activity 中定义一个上下文并在我的 AsyncTask 中使用它,但它给出了一个空引用?
在这里,我在我的主 Activity 中对其进行了测试,并且在我的 AsyncTask 中出现了同样的错误:
public class MainActivity extends AppCompatActivity {
public Context mContext;
public Context getContext(Context context) {
this.mContext = context;
mContext.getContentResolver();// null object reference error
return mContext;
}
【问题讨论】:
标签:
java
android
nullpointerexception
【解决方案1】:
AppCompatActivity 是一个 Context
您不需要该字段。只需使用 MainActivity.this 在该类中确实需要 Context 即可。
第二个问题 - 如果mContext.getContentResolver(); 抛出空指针,那么你只是将空上下文传递给该方法......
本质上,为什么要将参数传递给 get 方法?
public Context getContext(Context context) { <-- null
this.mContext = context; // <-- null
mContext.getContentResolver();// <-- Just used null... exception!
return mContext; // <-- null, and this is parameter you just provided, anyway...
或者,
How can getContentResolver() be called in Android?
直接拨打getContentResolver()即可。
【解决方案2】:
我看到的第一个问题是不存在getContentResolver() 方法,因此它会使对象引用为空,因为可能不存在这样的方法。如果有 getContentResolver 方法,那么您应该在示例中包含该方法:)
【解决方案3】:
您是否尝试设置或获取上下文?我会有一个单独的获取方法和另一个设置方法。
public void setContext(Context context) {
Objects.requireNotNull(context);
this.mContext = context;
mContext.getContentResolver();// Not sure if this should do anything?
}
public Context getContext() {
return mContext;
}