我想创建我的 sqlite 数据库,但我总是收到一个空指针异常。
我以这种方式启动我的 Databasehelper:
ContentProvider cp = new ContentProvider(this, this);
然后
public ContentProvider(Context _context, MainActivity activity) {
db = new DatabaseHelper(context);
Databasehelper 看起来像这样
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATENBANK_NAME = "serien.db";
private static final int DATENBANK_VERSION = 1;
// Table Names
private static final String TABLE_SERIEN = "serien";
private static final String TABLE_EPISODEN = "episoden";
// Common column names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_ISFAV = "isfav";
private static final String KEY_ENR = "episodennr";
private static final String KEY_SNR = "staffelnr";
private static final String KEY_SID = "serienid";
private static final String KEY_RELEASE = "release";
// serien table create statement
private static final String CREATE_TABLE_SERIEN = "CREATE TABLE "
+ TABLE_SERIEN + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME
+ " TEXT," + KEY_ISFAV + " INTEGER);";
// episoden table create statement
private static final String CREATE_TABLE_EPISODEN = "CREATE TABLE "
+ TABLE_EPISODEN + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ENR + " INTEGER ," +
KEY_SNR + " INTEGER ," + KEY_SID + " INTEGER ," + KEY_ID + " TEXT, FOREIGN KEY("+ KEY_SID + ") REFERENCES "+TABLE_SERIEN+"("+KEY_ID+"));";
private Context appContext;
public DatabaseHelper(Context context) {
super(context, DATENBANK_NAME, null, DATENBANK_VERSION);
appContext = context;
} // Db()
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("CREATE", CREATE_TABLE_SERIEN);
Log.d("CREATE", CREATE_TABLE_EPISODEN);
db.execSQL(CREATE_TABLE_SERIEN);
db.execSQL(CREATE_TABLE_EPISODEN);
} // onCreate()
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SERIEN);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EPISODEN);
onCreate(db);
} // onUpgrade()
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
然后我想用这种方法将一些数据写入数据库
public long createSerie(Serie serie) {
DatabaseHelper dbHelper = new DatabaseHelper(appContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, serie.getName());
values.put(KEY_ISFAV, serie.getIsFav());
// insert row
long serie_id = db.insert(TABLE_SERIEN, null, values);
return serie_id;
}
但问题来了。我总是在 ..getWritableDatabase() 行出现错误。
我已经阅读了很多关于这个问题的不同主题,但我没有尝试过。
有谁知道问题可能是什么?
非常感谢!