[英]Android existing sqlite database not found
使用AVD Manager在Android Studio中运行我的代码(我的应用)效果很好。 首先,我遇到了一个找不到数据库的问题,但后来我使用了Monitor(DDMS)并将文件放在正确的位置:/data/data/thePackagename/databases/database.sqlite
如果代码只是在某个地方找到数据库,我的应用程序就可以正常运行,所有Sqlite查询也可以正常运行!
现在,在安装了我的应用程序的真实电话(SGS4)上查找实际数据库时遇到了问题。 如果我错了,请纠正我,但是:我想我必须将数据库从SGS4上的某些存储卡复制/移动到以下位置: /data/data/thePackagename/databases/database.sqlite ...对吗? 现在我该怎么做? 也许我应该只将数据库放在内部或外部存储卡中,然后复制它,但是我不知道如何。 我已经关注了一些stackoverflow的帖子,但我真的不知道自己在做什么:)在真正的UE上运行时,我真的可以从资产文件夹中获取数据库吗? 该复制技巧甚至无法在AVD管理器UE中使用。 我想我需要一些专业帮助:)
我从这里使用了一些代码: 如何在Android应用程序中使用现有数据库
我已经尝试过了,但是没有用:
/**
* Creates a empty database on the system and rewrites it with your own database.
* By calling this method and empty database will be created into the default system path
* of your application so we are gonna be able to overwrite that database with our database.
*/
public void createDataBase() throws IOException {
//check if the database exists
boolean databaseExist = checkDataBase();
if (databaseExist) {
// Do Nothing.
} else {
Log.d("Haze", "Create DB...");
SQLiteDb = SQLiteDatabase.openOrCreateDatabase(DB_NAME_AND_PATH, null);
Log.d("Haze", "Just created DB...");
copyDataBase();
Log.d("Haze", "Just copied DB...");
}// end if else dbExist
} // end createDataBase().
/**
* 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
*/
public boolean checkDataBase() {
File databaseFile = new File(DB_PATH + DB_NAME);
return databaseFile.exists();
}
/**
* Copies your database from your 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 transferring byte stream.
*/
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 input file to the output file
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();
}
请帮助我解决这个问题:)
是的,您可以将数据库从资产文件夹复制到应用程序数据库文件夹。 但是,您需要了解该过程。 将使用扩展SqliteOpenHelper
类。 调用getReadableDatabase
或getWritableDatabase
它将检查以查看应用程序数据库文件夹中是否有数据库。 如果没有,它将从您扩展SqliteOpenHelper
类的databaseHelper
类调用onCreate
。 在这里,您将使用对copyDatabase
的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.