Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an Android library project have its own SQLite database?

Tags:

android

sqlite

I'm developing a library that will be able to be used across multiple apps. It serves the exact same function in each, and one of the goals of the library is to be as easy and painless to use as possible. In that way, I was hoping to use a SQLite db to store some important information relevant to the library, but NOT to the host app. I searched around and couldn't find anything confirming or denying the ability for libraries to have their own databases. Does anyone know if it is possible?

Thanks a lot.

like image 645
JMRboosties Avatar asked Oct 03 '12 18:10

JMRboosties


1 Answers

Well, that depends upon what you mean by "the ability for libraries to have their own databases".

There is nothing stopping an Android library project -- or even a plain Android-compiled JAR -- from using SQLiteDatabase, SQLiteOpenHelper, and kin. So, from a code standpoint, the library can have its own database. You will need a Context object from the host app, at least for use with SQLiteOpenHelper, though.

That is because, from a file standpoint, the library does not exist outside of its hosting app. Hence, the database file will be stored in the app's portion of internal storage by default. You will need to take some steps to try to minimize the odds of collisions on database file name (e.g., mangle your library's package name into the filename), so the host app does not attempt to accidentally work with your library's data. The Context is supplied to SQLiteOpenHelper mostly so that it can call methods like getDatabasePath() to figure out where to put the database file.

Also, bear in mind that the host app can access your database, just as it can access its own. Please make sure that you document the rules regarding this database (e.g., do not use it directly, but use the library's API instead).

like image 166
CommonsWare Avatar answered Oct 22 '22 00:10

CommonsWare