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:

  1. private static final String DATABASE_NAME = "testdatabase";
  2. private static final String DB_PATH = "/data/data/"+mContext.getPackageName()+"/databases/";
  3.  
  4. private boolean isDataBaseExist() {
  5.         File dbFile = new File(DB_PATH+DATABASE_NAME);
  6.         return dbFile.exists();
  7. }

If the check shows that the the database does not exist, a function like this will copy it:

  1. private void copyDataBase() throws IOException {
  2.         // Open your local db as the input stream
  3.         InputStream myInput = mContext.getAssets().open("databases/"+DATABASE_NAME);
  4.         // Path to the just created empty db
  5.         String outFileName = DB_PATH + DATABASE_NAME;
  6.         OutputStream myOutput = new FileOutputStream(outFileName);
  7.         // transfer bytes from the inputfile to the outputfile
  8.         byte[] buffer = new byte[1024];
  9.         int length;
  10.         while ((length = myInput.read(buffer)) > 0) {
  11.                 myOutput.write(buffer, 0, length);
  12.         }
  13.         // Close the streams
  14.         myOutput.flush();
  15.         myOutput.close();
  16.         myInput.close();
  17. }

I usually use SQLiteOpenHelper, so I add the methods above to the SQLiteOpenHelper class, and use the following code to open the database:

  1. try{
  2.         mDbHelper = new DatabaseHelper(mContext);
  3.         boolean isExist = mDbHelper.isDataBaseExist();
  4.         if(!mDbHelper.isDataBaseExist()){
  5.                 //get database, we will override it in next steep
  6.                 //but folders containing the database are created
  7.                 mDb = mDbHelper.getWritableDatabase();
  8.                 mDb.close();
  9.                 //copy database
  10.                 mDbHelper.copyDataBase();                              
  11.         }                                              
  12.         mDb = mDbHelper.getWritableDatabase();
  13. }catch(SQLException eSQL){
  14.         Log.e("log_tag","Can not open database");
  15. }
  16. catch (IOException IOe) {
  17.         Log.e("log_tag","Can not copy initial database");
  18. }

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.