How to put existing database in the .apk file?

前端 未结 3 967
再見小時候
再見小時候 2020-12-09 22:18

I have prebuild database of mostly string objects. I want to know how to put in my apk file so the database will be already created when the user installs the database.

3条回答
  •  猫巷女王i
    2020-12-09 22:49

    I've just started developing for Android, and was surprised to discover that bundling a static database is not easy to do. So I did the only reasonable thing: created a library which does just that. Example usage:

    import android.database.sqlite.SQLiteDatabase;
    import kiwidrew.staticdb.StaticDatabase;
    
    public class BlahBlah extends Activity {
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SQLiteDatabase db = StaticDatabase.openDatabase(this, "assets/foobar.db");
        // Do normal database stuff with 'db'...
      }
    }
    

    You get back a standard SQLiteDatabase object, with the only restriction being that it doesn't support writing. (Obviously!)

    Note that this will fail unless the database is stored in your .apk without compression. Add the sqlite database using the aapt -0 command or modify your build.xml to pass the flag to the tag...

    Get the code at http://bitbucket.org/kiwidrew/android-staticdb.

    Note: I've literally just finished writing this, and have only done very basic testing so far. Bug reports would be appreciated!

提交回复
热议问题