我想在外部存储中创建数据库,因此可以从应用和计算机轻松修改它。使用应用程序从数据库添加或读取时没有问题,但是当我在计算机或手机上使用文件浏览器时没有任何问题。此外,应该在Android /数据中的包目录也不存在。
以下是数据库的创建方式
public class DatabaseManager extends SQLiteOpenHelper {
public DatabaseManager(final Context context, String databaseName) {
super(new DatabaseContext(context), databaseName, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_WAYPOINTS_TABLE = "CREATE TABLE " + WAYPOINTS_TABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + " TEXT NOT NULL,"
+ KEY_CHARACTERISTIC + " TEXT NOT NULL,"
+ KEY_UKC + " FLOAT,"
+ KEY_LONGITUDE + " DOUBLE,"
+ KEY_LATITUDE + " DOUBLE"
+ ");";
db.execSQL(CREATE_WAYPOINTS_TABLE);
}
和DatabaseContext,它应该改变数据库位置:
public class DatabaseContext extends ContextWrapper {
private static final String DEBUG_CONTEXT = "DatabaseContext";
public DatabaseContext(Context base) {
super(base);
}
@Override
public File getDatabasePath(String name) {
String dbFile = Environment.getExternalStorageDirectory()
+ File.separator + "Android/data"
+ File.separator + getPackageName()
+ File.separator + name;
if (!dbFile.endsWith(".db")) {
dbFile += ".db" ;
}
File result = new File(dbFile);
if (!result.getParentFile().exists()) {
result.getParentFile().mkdirs();
}
if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN)) {
Log.w(DEBUG_CONTEXT, "getDatabasePath(" + name + ") = " + result.getAbsolutePath());
}
return result;
}
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN)){
Log.w(DEBUG_CONTEXT, "openOrCreateDatabase(" + name + ",,) = " + result.getPath());
}
return result;
}
当我打印DatabaseContext.getDatabasePath(databaseName)结果时,我得到了
/storage/emulated/0/Android/data/com.bearcave.passageplanning/database.db
按预期
问题是我做错了什么,数据库和包目录不在外部存储目录中创建?
答案 0 :(得分:1)
问题在于,自从Android级别11添加了新的开放openOrCreateDatabase
方法后,我还没有覆盖它。当我添加:
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
return openOrCreateDatabase(name, mode, factory);
}
DatabaseContext
开始正常工作,并且已在外部存储中创建数据库。