您必須在數據庫文件夾中第一次檢查日數據庫(沒什麼)
,那麼你必須複製.db的或.sqlite數據/數據/數據庫文件夾 並不僅僅是u能打開數據庫
這裏是我的示例代碼來做到這一點:
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
//boolean dbExist = false;
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// this method will check the existance of database
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
String myPath = DB_PATH + DB_NAME;
try {
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (Exception e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// copy the database file from asset folder to the DDMS database folder
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = _context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// open the database
public boolean openDataBase() throws SQLException {
String mPath = DB_PATH + DB_NAME;
// Log.v("mPath", mPath);
db = SQLiteDatabase.openDatabase(mPath, null,
SQLiteDatabase.CREATE_IF_NECESSARY);
return db != null;
}
http://stackoverflow.com/questions/9109438/how-to-use-an-existing-database-with-an-android-application/9109728#9109728 –