public class DBHelper extends SQLiteOpenHelper {
private static final int DB_VERSION=1;
private static final String DB_NAME="SAMPLE.db";
private static final String TABLE_NAME="events";
private static final String KEY_ID="sampleId";
private static final String KEY_TITLE="sampleTitle";
private static final String KEY_DATE="sampleDATE";
SQLiteDatabase dbEvents;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS sampleTable(sampleID INTEGER PRIMARY KEY AUTOINCREMENT,sampleTitle TEXT,sampleDATE BIGINT,trash INTEGER DEFAULT 0) ");
this.dbEvents=db;
}
public Integer deleteItem(Integer itemId){
Log.d("CURSOR:","IM HERE"+eventId);
if(dbEvents == null){
Log.d("CURSOR:","IM NOT INTIALIZING");
}
return null;
}
我正在进行IM而非正式化
并在我的Activity中调用[当单击删除按钮时]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper=new DBHelper(this);
}
public void deleteItem(int Id){
dbHelper=new DBHelper(this);
dbHelper.deleteEvent(Id);
}
我无法执行DB操作,因为它会抛出Null Pointer Exception。
提前致谢
答案 0 :(得分:1)
onCreate
方法时,将调用 getWritableDataBase()
。
来自方法getWritableDataBase()
的Javadocs,其中包含扩展 SQLiteOpenHelper
创建和/或打开将用于读写的数据库。第一次调用它时,将打开数据库并调用onCreate,onUpgrade和/或onOpen。
这意味着,这段代码
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS sampleTable(sampleID INTEGER PRIMARY KEY AUTOINCREMENT,sampleTitle TEXT,sampleDATE BIGINT,trash INTEGER DEFAULT 0) ");
this.dbEvents=db;
}
不会让你走得更远。由于通过调用getWritableDataBase
或getReadableDataBase
进行创建,因此返回SQLiteDatabase实例以执行SQLite操作。
因此,如果要访问数据库,则必须从活动中执行以下操作:
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDataBase();
db.query("SELECT * FROM " + sampleTable);