我要做的就是将db文件存储在Assets文件夹中,然后从中创建并复制数据。该代码在旧版本中运行完美,但在Pie中崩溃,请查看下面的代码。
public DBHelper(Context context, String DatabaseName) {
super(context, DatabaseName, null, DBVersion);
// TODO Auto-generated constructor stub
this.myContext = context;
this.DB_NAME = DatabaseName;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
SQLiteDatabase database = getReadableDatabase();
Complete_PATH = database.getPath();
database.close();
}
if (android.os.Build.VERSION.SDK_INT >= 4.1) {
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
Complete_PATH = DB_PATH + DB_NAME;
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
Complete_PATH = DB_PATH + DB_NAME;
}
checkDB = SQLiteDatabase.openDatabase(Complete_PATH, null, SQLiteDatabase.OPEN_READWRITE);
checkDB.disableWriteAheadLogging();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.v("database", "database exist" + "");
} else {
Log.v("database", "database not exist" + "");
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
OutputStream myOutput = new FileOutputStream(Complete_PATH);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
try {
myDataBase = SQLiteDatabase.openDatabase(Complete_PATH, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch (Exception e) {
// TODO: handle exception
}
}
public void closeDatabase() {
if (myDataBase != null)
myDataBase.close();
}
这是代码,请参阅。 当我运行查询选择数据时崩溃。
Error - Caused by: android.database.sqlite.SQLiteException: no such table: Schedule (code 1 SQLITE_ERROR): , while compiling: select * from Schedule where schedule_category ='schedule'