从IntentService构造函数打开数据库连接

时间:2012-11-21 13:32:02

标签: android sqlite service

尝试通过正常机制打开数据库连接时,nullpointerexecption处会抛出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的构造函数:

    public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    Log.e("DB_HELPER", "created");
}

这让我感到困惑的是最后一天左右我无法理解为什么上下文无效。此外,我已记录所有构造函数并正确创建所有对象,因此DBHelper不是空的。

除了使用上下文之外,我还尝试使用getBaseContext()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)]

1 个答案:

答案 0 :(得分:7)

您在IntentService生命周期中过早地设置了上下文。

覆盖onCreate并将其设置在那里:

@Override
public void onCreate() {
    super.onCreate();
    Log.d("ANALYSIS_SERVICE", "Service started");
    db = DatabaseFactory.getDefault(this);
}

然后在onHandleIntent中打开数据库连接:

@Override
protected void onHandleIntent(Intent intent) {
    // Logging
    Log.d("ANALYSIS_SERVICE", "Intent handled");

    try {
        db.openDB();
    } catch (Exception e) {
        Log.d("ANALYSIS_SERVICE", "Unable to open database");
        e.printStackTrace();
    }
}