How to have a default database
SDK Version:
M3 If you want to include a database with initial data in your apk, you have to insert the database file into the projects assets folder, then programmatically check if the database, and if it does not exists copy the one from the assets.
You will need a function to check if the database exists, fox example:
If the check shows that the the database does not exist, a function like this will copy it:
- // Open your local db as the input stream
- // Path to the just created empty db
- // transfer bytes from the inputfile to the outputfile
- byte[] buffer = new byte[1024];
- int length;
- while ((length = myInput.read(buffer)) > 0) {
- myOutput.write(buffer, 0, length);
- }
- // Close the streams
- myOutput.flush();
- myOutput.close();
- myInput.close();
- }
I usually use SQLiteOpenHelper, so I add the methods above to the SQLiteOpenHelper class, and use the following code to open the database:
- try{
- mDbHelper = new DatabaseHelper(mContext);
- boolean isExist = mDbHelper.isDataBaseExist();
- if(!mDbHelper.isDataBaseExist()){
- //get database, we will override it in next steep
- //but folders containing the database are created
- mDb = mDbHelper.getWritableDatabase();
- //copy database
- mDbHelper.copyDataBase();
- }
- mDb = mDbHelper.getWritableDatabase();
- Log.e("log_tag","Can not open database");
- }
- Log.e("log_tag","Can not copy initial database");
- }
As you can see each method handles the database as a general file, so it can be used for any file you want to have a default "value" in your application.





Comments
Re
Thank you for you post.
It's possible to use a db in assets in read only ???
Regards
Gilardh
Re
Good informative topic.
Thank you.
Online Pharmacies