Search code examples
androiddatabaseormactiveandroid

ActiveAndroid database location change dynamically


I am developing an Android App and thought of using an ORM to leverage some of the database work, i've seen a few and they all seem good for the job, now I only have one main issue left, i haven't found a way of setting the database location on runtime.

For example, im gonna talk about a common (and in this case, very real) scenario lets suppose your app needs to work completely offline, and the user downloads the database the app needs, a common guideline is to provide some sort of file explorer so the user can specify the data directory.

Well, let's suppose im using ActiveAndroid ORM, i've set up everything according to the guide, and I specify the name of the database in the AndroidManifest, i can even set a static path in there, say for example, "/mnt/sdcard/data/data.db" and it will work on using the existing database, i just haven't found the way of doing something like

ActiveAndroid.location = customLocation;

where customLocation is the path selected by the user on the Preferences, namely, the custom location of the database.

Any help appreciated.


Solution

  • I found a workaround that works for me, its nothing too complicated but i haven't seen this particular issue addressed nowhere.

    Instead of initializing your ActiveAndroid connection in the AndroidManifest via the

    android:name
    

    attribute, don't specify any name or metadata attribute there, now, the official documentation states you can initialize ActiveAndroid on runtime via

    ActiveAndroid.initialize(this)
    

    Well, there is a pretty handy class called Builder which can be accessed with a Configuration class, the one in ActiveAndroid, not the one in android.content.res, and with a Builder object you can specify a few things, namely, the

    setDatabaseName(String name)
    

    attribute, where you can then use the custom path of your database, and then initialize ActiveAndroid like this

    ActiveAndroid.initialize(builder.create())
    

    where the create() method returns a Configuration object

    And that does it! Now you can use that pre-populated database with ActiveAndroid wherever your users decided to place it.