Question

My question is I think quite simple but I don't think the answer will be... I have quite a lot of content to have in my application to make it run properly, and I'm thinking of putting all of it in a database, and distribute it in an embeded database with the application in the market. The only trouble is that I have no idea of how to do that. I know that I can extract a file .db from Eclipse DDMS with the content of my database, and I suppose I need to put it in the asset folder of my application, but then how to make the application use it to regenerate the application database? If you have any link to some code or help, that would be great. Thanks

Was it helpful?

Solution

Well to achieve what you're asking, you could put the .db file in your assets/ directory and copy it into place the first time you start your app.....

final String DB_DESTINATION = "/data/data/YOUR_PACKAGE_NAME/databases/MyDatabaseFile.db";

// Check if the database exists before copying
boolean initialiseDatabase = (new File(DB_DESTINATION)).exists();
if (initialiseDatabase == false) {

    // Open the .db file in your assets directory
    InputStream is = getContext().getAssets().open("MyDatabaseFile.db");

    // Copy the database into the destination
    OutputStream os = new FileOutputStream(DB_DESTINATION);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer)) > 0){
        os.write(buffer, 0, length);
    }
    os.flush();

    os.close();
    is.close();
}

Where "initialiseDatabase" is some flag indicating if the app has been launched for the first time.

Although, if you are looking at storing a lot of data, as you mentioned: I strongly recommend you avoid bloating the APK file with it, and use the Internet connection to download the database records (from a hosted server) after the app has been launched. This way you can show a progress bar indicating to the user why they are waiting a long time to start using the app. Making the APK especially large usually deters people from installing it in the first place.

OTHER TIPS

You can implement middle-of-the-road solution: Use approach above, but instead of distributing db file put it on server somewhere. In my experience getting files is only 10% of processing time, rest of it is parsing and serializing images to db

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top