public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "test.db";
private static final int DB_VERSION = 1;
private boolean DB_JUST_CREATED = false;
private Context _context;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
_context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("WOD", "onCreate firing");
DB_JUST_CREATED = true;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
SQLiteDatabase db = super.getWritableDatabase();
// Copy db from assets folder if db was just created.
if(DB_JUST_CREATED == true) {
Log.d("WOD", "Creating db");
try {
// Open InputStream to assets db.
InputStream inStream = _context.getAssets().open(DB_NAME);
// Open OutputStream to new db.
OutputStream outStream = new FileOutputStream(db.getPath());
//transfer bytes from the input-file to the output-file
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0)
{
outStream.write(buffer, 0, length);
}
//Close the streams
outStream.flush();
outStream.close();
inStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return db;
}
}
我尝试在几个不同的活动中创建一个 DatabaseHelper 对象,每次都是一样的,onCreate()被触发,然后它创建一个新数据库。我检查了 DDMS 文件资源管理器,果然,数据库在创建后仍然存在,即使我强制停止应用程序,所以甚至不应该调用 onCreate。这里发生了什么?