我是Android的新手,刚开始使用我的第一个应用程序。任何帮助是极大的赞赏。
我创建了一个dbhelper类,但它失败并出现NullPointer
异常。当我尝试调试时,上下文始终显示为null,因此mDatabase也为null。
以下是我的代码。
public class PharmaExpDBHelper {
static final String DB_NAME = "pharmaApp.db";
static final int VERSION = 1;
private SQLiteDatabase db;
private Context context;
public PharmaExpDBHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE pharmacy_list(id integer primary key autoincrement, name text);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(PharmaExpDBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS" + " pharmacy_list");
onCreate(db);
}
}
}
答案 0 :(得分:1)
发布的代码我没有看到任何明显错误。由于您说Context
为null,因此应确保实例化此类的位置正在传递有效的Context
实例。
如果有人通过null IllegalArgumentException
作为完整性检查,则抛出Context
会有所帮助。
答案 1 :(得分:0)
代替此代码
public PharmaExpDBHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
}
使用一个返回SQliteDatabase db的方法
public SQLiteDatabase getDBHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
return this.db
}
现在在您的活动中访问它
SQLiteDatabase db=PharmaExpDBHelper class Obejct.getDBHelper(context);
答案 2 :(得分:0)
公共类PharmaExpDBHelper {
static final String DB_NAME = "pharmaApp.db";
static final int VERSION = 1;
private SQLiteDatabase db;
private PharmaExpDBHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE pharmacy_list(id integer primary key autoincrement, name text);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(PharmaExpDBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS" + " pharmacy_list");
onCreate(db);
}
public PharmaExpDBHelper open(){
db=PharamExpDBHelper.getWriteableDatabase();
return db;
}
}
现在通过
访问您的Activity中的此数据库PharmaExpDBHelper dbhHelper=new PharmaExpDBHelper(this);
db.open();
试试这段代码