I needed to prepopulate a database file for a Phonegap project that I was working on. My database was 10mb, so loading it from a SQL file via AJAX on the first launch was not an option. After many hours, I finally figured out how to do it. Enjoy! I hope this can be useful to some of you.

Materials Required:

  • PhoneGap
  • https://github.com/chbrody/Cordova-SQLitePlugin/
    1. Android Version, I used version downloaded on 8/7/2012.
    2. Versions differed a lot for me in updates. For example, the latest version automatically appends “.db” to your window.sqlitePlugin.openDatabase() function.

Steps to take:

    • Place your SQLite Database file in /assets directory for your project. DO NOT PUT IT IN /assets/www/.
      1. My database in this example is called “vvmf.db”.
    • In our main Activity file (the one that extends DroidGap), we will need to copy the database from the /assets/ directory to the DB directory if necessary. To do this, use code similar to the following below:
          try 
          {
              File dbFile = getDatabasePath("vvmf.db");
              if(!dbFile.exists()){
                  this.copy("vvmf.db",dbFile.getAbsolutePath());
              }
           } 
           catch (Exception e)
           {
           e.printStackTrace();
           }
      
      //And our copy function:
      
         void copy(String file, String folder) throws IOException 
          {
           File CheckDirectory;
           CheckDirectory = new File(folder);
      
           String parentPath = CheckDirectory.getParent();
      
           File filedir = new File(parentPath);
           if (!filedir.exists()) {
               if (!filedir.mkdirs()) {
                   return;
               }
           }
      
              InputStream in = this.getApplicationContext().getAssets().open(file);
              File newfile = new File(folder);
              OutputStream out = new FileOutputStream(newfile);
      
              byte[] buf = new byte[1024];
              int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
              in.close(); out.close();
          }

 

  • Make sure chbrody’s SQLitePlugin is installed properly.
    • Get it from https://github.com/chbrody/Cordova-SQLitePlugin/
  • In your main JS file, in your “deviceready” event listener, use the following function call to load your database file:
    1. window.sqlitePlugin.openDatabase(“vvmf”, “1.0”, “vvmf”, 20000);

That’s it, Enjoy!

-Scott Buckel – Email me scott at CorporateZen dot com

Add Comment

Your email address will not be published. Required fields are marked *

This blog is meant for Corporate Zen employees to write about a variety of topics. Posts may contain information and views not directly related to Corporate Zen!