我在assert /文件夹中有一个数据库文件,我用代码复制数据库。 但在将其复制到设备后,表格丢失了。只有当我在Android P(8.1)中运行应用程序并且它与其他Android版本一起正常工作时我才检查Nougat并且它工作正常。
如果Android P有任何新的更新,请帮忙。??
复制数据库代码:
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
//do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
//database does't exist yet.
e.printStackTrace();
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
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();
}
答案 0 :(得分:2)
我通过在this.getReadableDatabase()之后添加this.close()解决了android P中的问题
this.getReadableDatabase();
this.close();
我希望此解决方案对您有用。
答案 1 :(得分:0)
要解决此问题,请尝试 SQLiteHelper onUpgrade()
中的以下代码:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion>oldVersion)
copyDatabase();
}
答案 2 :(得分:0)
private final static String DB_PATH = "/data/data/packageName/databases/";
DbHelper.java
//Database HelperClass Constuctor
public DBHelper(Context context)
{
super(context, "db.sqlite", null, 1);
Log.e(TAG, "DBHelper: construction");
this.context = context;
dbFile = new File(DB_PATH + dbName);
if (!dbFile.exists())
{
SQLiteDatabase db = super.getReadableDatabase();
db.close();
copyDataBase(db.getPath());
}
}
在调用this.close();
之后通过调用getReadableDatabase();
关闭数据库