仅在Android P(8.1)模拟器中出错]:android.database.sqlite.SQLiteExcept



我在assert/文件夹中有一个数据库文件,我使用了复制数据库的代码。 但是将其复制到设备后,表丢失了。只有当我在 Android P(8.1( 中运行应用程序并且它与其他 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();
}

我在android P中通过在this.getReadableDatabase((之后添加this.close((解决了这个问题

this.getReadableDatabase();
this.close();

我希望这个解决方案对您有用。

要解决此问题,请尝试SQLiteHelper onUpgrade()中的以下代码:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion>oldVersion)
  copyDatabase();
}
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());
        }    
 }

在调用getReadableDatabase();后通过调用this.close();关闭数据库

最新更新