在 Android P 之前,我的代码一切正常,但是在 Android P 上,我在处理数据库时遇到了很多问题。
我有一些 .db SQLite 数据库文件存储在 assets 文件夹中,我将它们导入到 Android 的数据库空间中,并且在 Android P 之前一直都可以工作。但是在 Android P 上,我遇到了这个异常:SQLite: No Such Table Error
我在 StackOverflow 上搜索并找到了这个问题的解决方案,我尝试了该答案的方法:Android P - 'SQLite: No Such Table Error' after copying database from assets
但现在我又遇到了另一个问题,仍然无法解决。现在,每次我尝试检查数据库是否已存在时,此代码总是返回 true,因此我从未创建数据库。即使数据库尚未创建,即使应用程序最近安装:
private boolean checkIfDBExists() {
File dbFile = new File(DB_COMPLETE_PATH);
return dbFile.exists();
}
我的源代码是之前引用的Stack Overflow问题中被接受回答的源代码。
获取数据库路径的新Android P要求:
public static String getDatabasePath(String fileNname){
MySQLiteOpenHelper helper = new MySQLiteOpenHelper(ApplicationContextProvider.getContext(), fileNname);
SQLiteDatabase database = helper.getReadableDatabase();
String path = database.getPath();
database.close();
return path;
}
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public 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) {
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
db.disableWriteAheadLogging();
}
}
我的DBHelper类:
public class DbHelper extends SQLiteOpenHelper{
private String DB_NAME;
private String DB_COMPLETE_PATH;
private SQLiteDatabase mDataBase;
private static final int DATABASE_VERSION = 1;
public DbHelper(String name) throws IOException {
super(ApplicationContextProvider.getContext(), name+".db", null, DATABASE_VERSION);
this.DB_NAME = name+".db";
this.DB_COMPLETE_PATH = Util.getDatabasePath(DB_NAME);
boolean mustOverWriteDB;
if (checkIfDBExists()==false) {
createDataBase();
}
openDataBase();
}
private void createDataBase() throws IOException {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void copyDataBase() throws IOException {
InputStream myInput = App.getInstance().getAssetsFile(DB_NAME);
String outFileName = DB_COMPLETE_PATH;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
}