我在已经定义的上下文变量上得到android.content.Context android.content.Context.getApplicationContext()' on a null object reference
。我正在关注Android开发的Big Nerd Ranch指南,但是代码给了我这个看似毫无根据的错误。
这是我声明我的Context变量mContext
:
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes = new ArrayList<>();
private Context mContext;
private SQLiteDatabase mDatabase;
...
}
但是这行代码抛出了一个空对象引用:
public CrimeLab(Context context) {
mContext = context.getApplicationContext(); <- This one
mDatabase = new CrimeBaseHelper(mContext)
.getWritableDatabase();
mCrimes = new ArrayList<>();
}
这是堆栈跟踪。我尝试了不同的方式来声明上下文,但它都给出了同样的错误。
Process: myapp.onur.criminalintent, PID: 5095
java.lang.RuntimeException: Unable to start activity ComponentInfo{myapp.onur.criminalintent/myapp.onur.criminalintent.CrimeListActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at myapp.onur.criminalintent.CrimeLab.<init>(CrimeLab.java:26)
编辑这是我的整个CrimeLab.java类
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes = new ArrayList<>();
private Context mContext;
private SQLiteDatabase mDatabase;
public void addCrime(Crime c){
mCrimes.add(c);
}
public CrimeLab(Context context) {
mContext = context.getApplicationContext();
mDatabase = new CrimeBaseHelper(mContext)
.getWritableDatabase();
mCrimes = new ArrayList<>();
}
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}return sCrimeLab;
}
public List<Crime> getCrimes() {
return mCrimes;
}
public Crime getCrime(UUID id){
for (Crime crime : mCrimes){
if(crime.getID().equals(id)){
return crime;
}
}
return null;
}
}
答案 0 :(得分:1)
某处,您正在调用new CrimeLab(null)
或正在将null
传递给CrimeLab
构造函数。
在您现在更新的问题中,您要在:
中创建新的CrimeLab
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}return sCrimeLab;
}
因此,传递给Context
的{{1}}为get()
。因此,找到您呼叫null
的位置并修复参数,使其不是CrimeLab.get()
。
答案 1 :(得分:0)
我解决了。问题出在另一个班级。它没有明确表示null
,但它传递了一个错误的变量。我所要做的就是将其删除。