您的问题是,您试图使用不包含数据库名称的路径打开。
i、 e.无法打开14用于
/data/user/0/com.example.hack.corrector/databases/
打开时应尝试打开
/data/user/0/com.example.hack.corrector/databases/ztr.db
不使用完整路径将导致两个问题,这很可能导致混淆。
-
当您检查数据库是否存在时,将发出消息(请注意,由于数据库永远不会被找到(打开),因此每次都会复制数据库)
-
当您尝试打开数据库时,也会发出这些消息,后者失败。
在这两种情况下,正确的用法应该是DB\u PATH+DB\u NAME,而不仅仅是DB\u PATH。
以下是重写的数据库处理程序,以合并上述内容,但也将对数据库的检查更改为对文件的检查,以便不显示非错误的打开错误14(从资产文件复制数据库时)。
:-
public class VocabDatabase extends SQLiteOpenHelper {
private static String DB_PATH_ALT;
private static String DB_NAME = "ztr.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
public VocabDatabase(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
this.DB_PATH_ALT = context.getDatabasePath(DB_NAME).getPath();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBaseAlt();
if (dbExist) {
} else {
this.getWritableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBaseAlt() {
File chkdb = new File(DB_PATH_ALT);
return chkdb.exists();
}
private boolean checkDataBase() {
this.getReadableDatabase();
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(
DB_PATH_ALT,
null,
SQLiteDatabase.OPEN_READWRITE
);
} catch (SQLiteException e) {
e.printStackTrace();
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
OutputStream myOutput = new FileOutputStream(DB_PATH_ALT);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
myDataBase = SQLiteDatabase.openDatabase(
DB_PATH_ALT,
null,
SQLiteDatabase.OPEN_READWRITE
);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
try {
copyDataBase();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
}
public long insert(String table, String nullColumnHack, ContentValues contentValues) {
SQLiteDatabase db = this.getWritableDatabase();
return db.insert(table, nullColumnHack, contentValues);
}
public Cursor rawQuery(String string, String[] selectionArguments) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(string, selectionArguments);
}
}