从资产复制数据库后,Android P-"SQLite:无此类表错误" [英] Android P - 'SQLite: No Such Table Error' after copying database from assets
问题描述
我的应用程序资产文件夹中保存了一个数据库,并在应用程序首次打开时使用以下代码复制该数据库.
I have a database saved in my apps assets folder and I copy the database using the below code when the app first opens.
inputStream = mContext.getAssets().open(Utils.getDatabaseName());
if(inputStream != null) {
int mFileLength = inputStream.available();
String filePath = mContext.getDatabasePath(Utils.getDatabaseName()).getAbsolutePath();
// Save the downloaded file
output = new FileOutputStream(filePath);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1) {
total += count;
if(mFileLength != -1) {
// Publish the progress
publishProgress((int) (total * 100 / mFileLength));
}
output.write(data, 0, count);
}
return true;
}
上面的代码运行没有问题,但是当您尝试查询数据库时,您会得到一个SQLite:没有这样的表异常.
The above code runs without problem but when you try to query the database you get an SQLite: No such table exception.
此问题仅发生在Android P中,所有早期版本的Android均可正常工作.
This issue only occurs in Android P, all earlier versions of Android work correctly.
这是Android P的已知问题还是有所更改?
Is this a known issue with Android P or has something changed?
推荐答案
这个问题似乎导致Android P崩溃的频率比以前的版本高得多,但这并不是Android P本身的错误.
This issue seems to lead to a crash much more often on Android P than on previous versions, but it's not a bug on Android P itself.
问题在于,将值分配给String filePath
的行打开了与数据库的连接,当您从资产中复制文件时,该连接保持打开状态.
The problem is that your line where you assign the value to your String filePath
opens a connection to the database that remains open when you copy the file from assets.
要解决此问题,请替换行
To fix the problem, replace the line
String filePath = mContext.getDatabasePath(Utils.getDatabaseName()).getAbsolutePath();
使用代码获取文件路径值,然后关闭数据库:
with code to get the file path value and then close the database:
MySQLiteOpenHelper helper = new MySQLiteOpenHelper();
SQLiteDatabase database = helper.getReadableDatabase();
String filePath = database.getPath();
database.close();
并添加一个内部帮助器类:
And also add an inner helper class:
class MySQLiteOpenHelper extends SQLiteOpenHelper {
MySQLiteOpenHelper(Context context, String databaseName) {
super(context, databaseName, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
这篇关于从资产复制数据库后,Android P-"SQLite:无此类表错误"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!