当试图通过正常机制打开数据库连接时,nullpointerexecption
会抛出a dbhelper.getWritableDatabase
。
问题似乎源于IntentService
我传入的上下文。
public AnalysisService() {
super("AnalysisService");
Log.d("ANALYSIS_SERVICE", "Service started");
try{
db = new DBAdapter(this)
db.openDB();
}catch(Exception e){
Log.d("ANALYSIS_SERVICE", Arrays.toString(e.getStackTrace()));
Log.e("ANALYSIS_SERVICE", e.toString());
}
}
该db.open
方法在这里执行:
public class DBAdapter implements Database {
protected Context context;
protected SQLiteDatabase db;
private DatabaseHelper dbHelper;
public DBAdapter(Context context) {
this.context = context;
Log.e("DB_ADAPTER", "CREATED");
}
/**
* Opens a database connection.
* @return
* @throws SQLException
*/
@Override
public DBAdapter openDB() throws SQLException {
dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase(); //NULLP EXCEPTION THROWN HERE
return this;
}
如果它对dbHelper
is 的构造函数有帮助:
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("DB_HELPER", "created");
}
这让我在最后一天感到困惑,所以我不明白为什么上下文是无效的。此外,我还记录了所有构造函数,并且所有对象都被正确创建,因此 DBHelper 并非为空。
除了像这样使用上下文之外,我还尝试使用getBaseContext()
and getApplicationContext()
,两者都导致相同的错误。
从调试打印堆栈跟踪,我得到:
11-21 13:23:45.419: D/ANALYSIS_SERVICE(3930):
[android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221),
android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:166),
com.emotifi.database.DBAdapter.openDB(DBAdapter.java:42),
com.emotifi.analysis.AnalysisService.<init>(AnalysisService.java:45),
java.lang.Class.newInstanceImpl(Native Method),
java.lang.Class.newInstance(Class.java:1319),
android.app.ActivityThread.handleCreateService(ActivityThread.java:2234),
android.app.ActivityThread.access$1600(ActivityThread.java:123),
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201),
android.os.Handler.dispatchMessage(Handler.java:99),
android.os.Looper.loop(Looper.java:137),
android.app.ActivityThread.main(ActivityThread.java:4424),
java.lang.reflect.Method.invokeNative(Native Method),
java.lang.reflect.Method.invoke(Method.java:511),
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817),
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584),
dalvik.system.NativeStart.main(Native Method)]