我已经有几天这个问题了,在代码中确实看不到问题,因此非常感谢您多加关注。
我通过简单地创建一个新的数据库管理器对象并打开管理器数据库来启动该应用程序。
DBManager db_manager = new DBManager(this);
db_manager.open()
然后,应用应执行简单的插入事务,但会引发错误:
02-11 18:13:30.350: E/AndroidRuntime(8961): Caused by: java.lang.NullPointerException
02-11 18:13:30.350: E/AndroidRuntime(8961): at com.test.DB.DBManager$DatabaseHelper.onCreate(DBManager.java:44)
02-11 18:13:30.350: E/AndroidRuntime(8961): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:106)
02-11 18:13:30.350: E/AndroidRuntime(8961): at com.test.DB.DBManager.open(DBManager.java:61)
02-11 18:13:30.350: E/AndroidRuntime(8961): at com.test.DB.Display.onCreate(Display.java:26)
02-11 18:13:30.350: E/AndroidRuntime(8961): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
02-11 18:13:30.350: E/AndroidRuntime(8961): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
DatabaseHelper类:
class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
the_db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
DBManager方法open()引起了问题。
public DBManager(Context c){
this.context = c;
helper = new DatabaseHelper(context);
}
// Makes the_db available to the Manager class.
public DBManager open() throws SQLException{
the_db = helper.getWritableDatabase();
return this;
}
最佳答案
尝试:
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
}
您已经通过
onCreate()
方法获取了数据库,该数据库是SQLiteDatabase参数db,必须使用它。编辑:
之所以得到
NullPointerException
,是因为您在executeSQL()
中的the_db
上调用DBManager
,可能是这样声明的:SQLiteDatabase the_db;
要么
SQliteDatabase the_db = null;
因此,当您实际进入
onCreate(SQLiteDatabase db)
时,您可以在null上调用executeSQL()
。 DBManager
的代码应如下所示:public class DBManager {
//the actual database you will use to insert,select etc after the getWritableDatabase() call
private SQLiteDatabase the_db;
private Context context;
private DatabaseHelper helper;
public DBManager(Context c) {
this.context = c;
helper = new DatabaseHelper(context);
}
// Makes the_db available to the Manager class.
public DBManager open() throws SQLException {
the_db = helper.getWritableDatabase();
return this;
}
class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, "something.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// the db is the SQLiteDatabase that android will offer you
// and you must use it!
db.execSQL("CREATE TABLE nametables(name TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
关于android - Android:getWriteableDatabase()错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9242823/