Embed a database in the .apk of a distributed application [Android]

前端 未结 2 1709
南方客
南方客 2020-12-05 03:41

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 thinki

相关标签:
2条回答
  • 2020-12-05 04:11

    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.

    0 讨论(0)
  • 2020-12-05 04:21

    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

    0 讨论(0)
提交回复
热议问题