7

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 Answers 3

11

I found a good example of this: Using your own SQLite database in Android applications

Basically, you export the created database as an sql-file and store it in the assets-folder. On the first program start, you import the data of the file into your final database.

I think it's the best approach, however your data will be there twice in the apk and the db, using some more storage space.

0
8

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 <nocompress extension="db" /> flag to the <aapt> 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!

0
1

There are no any simple way to read database from assets directly. You should copy your database from assets to data folder in the first run, then when every time your app starts up, you should check database in the data folder and copy it again if the database does not exist.

These steps help you:

1) Execute these commands on your database, if android_metadata table does not exist in your database, android could not open your database.:

CREATE TABLE android_metadata(locale TEXT DEFAULT 'en_US')
INSERT INTO android_metadata VALUES('en_US')

2) Chunk your database because android does not support reading a file that more than 1 MB size from assets.

This python code chunks your database:

def chunk_file(file_name):
    input_file = open(file_name, "rb")

    chunk_counter = 0;
    while True:
        chunk = input_file.read(512 * 1024) # 512 KB
        if chunk:
            output_file_name = file_name + "." + str(chunk_counter).zfill(4)

            output_file = open(output_file_name, "wb")
            output_file.write(chunk)
            output_file.close()

            chunk_counter += 1
        else:
            break

    input_file.close()
    return

# Input: database.db
# Output: database.db.0000, database.db.0001, database.db.0002, ...
chunk_file("database.db")

Then put database.db.0000, database.db.0001, database.db.0002, ... in the assets folder.

3) Check database exists in the data folder when app starts up.

public static boolean databaseExists() {

    boolean result = false;

    SQLiteDatabase checkDB = null;

    try {
        checkDB = SQLiteDatabase.openDatabase(
                getApplicationContext().getFilesDir().getPath() + "/database.db",
                null, SQLiteDatabase.OPEN_READONLY);
        result = true;
    } catch (SQLiteException exception) {
        result = false;
    }

    if (checkDB != null) {

        checkDB.close();

    }

    return result;
}

4) If database does not exist in data folder, copy database from assets to data folder.

public static void copyDatabase() throws IOException {
    AssetManager assets = getApplicationContext().getAssets();

    // database.db.0000, database.db.0001, database.db.0002, ... --> databaseChunks.
    String[] databaseChunks = assets.list("");
    Arrays.sort(databaseChunks);

    OutputStream databaseStream = new FileOutputStream(
            getApplicationContext().getFilesDir().getPath() + "/database.db");

    for (int i = 0; i < databaseChunks.length; i++) {
        String databaseChunkName = databaseChunks[i];

        InputStream chunkStream = assets.open(databaseChunkName);

        int length;
        byte[] buffer = new byte[1024];
        while ((length = chunkStream.read(buffer)) > 0) {
            databaseStream.write(buffer, 0, length);
        }

        chunkStream.close();
    }

    databaseStream.close();

    return;
}

5) You can connect to the database now:

SQLiteDatabase database = SQLiteDatabase.openDatabase(
            getApplicationContext().getFilesDir().getPath() + "/database.db",
            null, SQLiteDatabase.OPEN_READONLY);
// ...
database.close();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.