首次在模拟器中启动应用程序时出现问题。当我运行应用程序时,我的资产文件夹中的数据库文件应该复制并读取。它也会复制数据库文件WITH database.sqlite.journal文件(对我来说很奇怪,为什么?)。但是应用程序崩溃了。
之后我总是要从数据库文件夹中删除这两个文件并将数据库文件拉到那里。之后它运行顺利,直到我使用相同的模拟器。
为什么会这样?我的databasehelper类的代码如下。我做错了吗?
/**
* Creates a empty database on the system and rewrites it with your own
* database.
*
* @throws IOException
*/
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing-database already exists
Log.i("DB....", "database available....");
} else {
// By calling this method and empty database will be created into
// the default system path
// of the application so we will be able to overite the database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error Copying database");
}
Log.i("DB..", "database created.....");
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDataBase = null;
try {
String Path = DB_PATH + DB_NAME;
checkDataBase = SQLiteDatabase.openDatabase(Path, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
Log.e("CheckDb", "DB not found");
// database does't exist yet.
}
if (checkDataBase != null) {
checkDataBase.close();
}
return checkDataBase != null ? true : false;
}
/**
* Copies your database from local assets-folder to the just created empty
* database in the system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
*
* @throws IOException
*/
private void copyDataBase() throws IOException {
// Open your local database as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// path to just created empty db.
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream.
OutputStream myOutput = new FileOutputStream(outFileName);
Log.i("Database", "New database is being copied to device!");
// 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 stream.
myOutput.flush();
myOutput.close();
myInput.close();
Log.i("Database", "New database has been copied to device!");
}
/**
* Open the database
*
* @throws SQLException
*/
public void openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(path, null, 0);
Log.i("DB....", "database opened....");
}
public synchronized void close() {
if (mInstance != null)
db.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
检查变量
private static String DB_PATH = "/data/data/PACKAGENAME/databases/";
private static String DB_NAME = "DBNAME.db";