Reputation: 1082
I wanted to create database in external storage, so it can easily be modified from app and computer. There is no problem when I add or read from database using application, but there is nothing when I use file explorer on computer or phone. Moreover, the package directory, which should be in Android/data also doesn't exist.
Here is how database is created
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);
}
And DatabaseContext, which is supposed to change database location:
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;
}
When I printed DatabaseContext.getDatabasePath(databaseName) result I got
/storage/emulated/0/Android/data/com.bearcave.passageplanning/database.db
as expected
The question is what am I doing wrong, that database and package directory are not created in external storage directory?
Upvotes: 0
Views: 205
Reputation: 1082
The problem was that since Android level 11 new open openOrCreateDatabase
method was added and I haven't overrode it. When I added:
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
return openOrCreateDatabase(name, mode, factory);
}
DatabaseContext
started to work properly and database has been created in external storage.
Upvotes: 1