Search code examples
androidsqliteopenhelpergreendao

How to let greenDAO to create the Database on sdcard ? - Android


I want to use greenDAO as sqlite DB ORM

but my database should be located on sdcard in a specific folder like /sdcard/myapp/database.sqlite

So how to choose the folder of database to be created in using greenDAO ?


Solution

  • For quite some time (Android 2.2 I believe) it is possible use SQLiteOpenHelper with an absolute path. So for the greendao sample app (only tested with Android 4.4 and 5.0)

    File path = new File(Environment.getExternalStorageDirectory(), "my_sdcard_dir/deeper_dir/notes-db");
    path.getParentFile().mkdirs();
    
    DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, path.getAbsolutePath(), null);
    db = helper.getWritableDatabase();
    
    daoMaster = new DaoMaster(db);
    ...
    

    Alternatively, as the DaoMaster only needs the database itself :

    File path = new File(Environment.getExternalStorageDirectory(), "my_sdcard_dir/deeper_dir/notes-db");
    path.getParentFile().mkdirs();
    
    db = SQLiteDatabase.openOrCreateDatabase(path, null);
    DaoMaster.createAllTables(db, true);
    
    daoMaster = new DaoMaster(db);
    ...