简单地说,这是我的课
public class sqlite extends SQLiteOpenHelper{
public SQLiteDatabase db;
public sqlite(Context context , String db_name , int db_version){
super(context, db_name, null, db_version, null);
try{this.db=getWritableDatabase();}catch(Exception e){this.db=getReadableDatabase();}
}当我调用新的sqlite(*****);时,函数getWritableDatabase()和getReadableDatabase()总是会导致错误(空对象引用上的NullPointerException),那么,要成功地实现这些函数,必须调用的正确引用是什么?
Edit我找到了一个解决方案,但我仍然犹豫不决,为什么上面的代码不能工作?解决方案是将getWritableDatabase()从sqlite (扩展SQLiteOpenHelper)构造函数移到它自己的操作方法,即:在CRUD方法之前,如果从构造函数调用它,我不知道它为什么会失败
发布于 2016-09-17 13:01:47
您需要从构造函数中删除对getWritableDatabase的调用。相反,无论何时您想使用数据库助手,您都可以简单地调用sqlite类的实例(我强烈建议您将其重命名为有意义的东西--遵循适当的Java类命名约定)。
//Here is an example (using this from an Activity or some other class):
//pass appropriate values for the arguments...
sqlite myDatabaseHelper = new sqlite(context, db_name, db_version);
//here you can get the writable-database object
SQLiteDatabase sqlDB = myDatabaseHelper.getWritableDatabase();
//from here you can perform your database operations - like querying/inserting values, etchttps://stackoverflow.com/questions/39546613
复制相似问题