我想創建數據庫和所有數據ONCE並在稍後需要時更新一些數據。在我閱讀的大多數教程中,他們使用兩個類:一個擴展SQLiteOpenHelper,另一個簡化操作數據。例如:Android sql創建數據庫一次
public class EventsData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INT, " + TITLE + " TEXT, " + UNLOCK + " INT)";
private static final String DATABASE_UPGRADE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public EventsData(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_UPGRADE);
onCreate(db);
}
}
public class DataHelper {
private static final String[] FROM = {ID, TITLE, UNLOCK};
//private static final String ORDER_BY = UNLOCK + " DESC";
private Context context;
private SQLiteDatabase db;
private EventsData eventsData;
public DataHelper(Context context) {
this.context = context;
eventsData = new EventsData(this.context);
}
public void addEvent(int id, String name, int unlocked) {
db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ID, id);
cv.put(TITLE, name);
cv.put(UNLOCK, unlocked);
db.insertOrThrow(TABLE_NAME, null, cv);
}
public void updateEvent(int id, String name, int unlocked) {
db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ID, id);
cv.put(TITLE, name);
cv.put(UNLOCK, unlocked);
db.update(TABLE_NAME, cv, ID + "=" + id, null);
}
public Cursor getEvent() {
db = eventsData.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, null);
return cursor;
}
public StringBuilder showEvent(Cursor cursor) {
StringBuilder sb = new StringBuilder();
while (cursor.moveToNext()) {
String id = cursor.getString(0);
String title = cursor.getString(1);
String unlock = cursor.getString(2);
sb.append(id).append(": ");
sb.append(unlock).append(": ");
sb.append(title).append("\n");
}
return sb;
}
public void deleteAll() {
db = eventsData.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
}
}
在我的主要活動中,我創建DataHelper的一個實例,並調用的addEvent()來創建和數據添加到數據庫中。但是,每次應用程序啓動時,即使我調用updateEvent(),也會「重置」所有數據。
只是想創建一次數據庫。我想使用我創建的DataHelper類來簡化更新數據的工作。 – semajhan 2011-01-08 00:18:52