您必须首先检查数据库文件夹中的数据库(什么都没有)
然后你必须将 .db 或 .sqlite 复制到 data/data/databases 文件夹,并且只有你可以打开数据库
这是我的示例代码:
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;
}