Tutorial: Shipping database with Android applications

Most all of the Android examples and tutorials out there assume you want to create and populate your database at runtime and not to use and access an independent, preloaded database with your Android application.

This tutorial shows, you can take your own SQLite database file from the “assets” folder and copies into the system database path of your application so the SQLiteDatabase API can open and access it normally.

1. Preparing the SQLite database file.

Assuming you already have your SQLite database created, we need to do some modifications to it.

If you don’t have a SQLite Manager We recommend you to download the opensource SQLite Database Browser available for Win/Linux/Mac.

Open your database and add a new table called “android_metadata”, you can execute the following SQL statement to do it:
[sourcecode language=”java”]
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT ‘en_US’)
[/sourcecode]

Now insert a single row with the text ‘en_US’ in the “android_metadata” table:
[sourcecode language=”java”]
INSERT INTO "android_metadata" VALUES (‘en_US’)
[/sourcecode]

Then, it is necessary to rename the primary id field of your tables to “_id” so Android will know where to bind the id field of your tables.

You can easily do this with SQLite Database Browser by pressing the edit table button Edit Table, then selecting the table you want to edit and finally selecting the field you want to rename.

After renaming the id field of all your data tables to “_id” and adding the “android_metadata” table, your database it’s ready to be used in your Android application.

Note: in this image we see the tables “EMP_TABLE” with the id field renamed to “_id” and the just added table “android_metadata“.

2. Copying, opening and accessing your database in your Android application.

Create project named “com.mobisys.android.External_to_application” with the activity “CopyDbActivity".
"main.xml" will contain:
[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<Button android:id="@+id/button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Copy Database">
</Button>

</LinearLayout>
[/sourcecode]

Now just put your database file in the "assets" folder of your project and create a DatabaseHelper class by extending the SQLiteOpenHelper class.

DatabaseHelper class contains:
[sourcecode language="java"]
package com.mobisys.android.External_to_application;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

//The Android's default system path of your application database.
String DB_PATH =null;

private static String DB_NAME = "extenalDB";

private SQLiteDatabase myDataBase;

private final Context myContext;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DatabaseHelper(Context context) {

super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH="/data/data/"+context.getPackageName()+"/"+"databases/";
}

/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{

boolean dbExist = checkDataBase();

if(dbExist){
//do nothing - database already exist
}else{

//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();

try {
<div style="display:none"></div>
copyDataBase();

} catch (IOException e) {

throw new Error("Error copying database");

}
}

}

/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){

SQLiteDatabase checkDB = null;

try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}catch(SQLiteException e){

//database does't exist yet.

}

if(checkDB != null){

checkDB.close();

}

return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{

//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

public void openDataBase() throws SQLException{

//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {

if(myDataBase != null)
myDataBase.close();

super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
//return cursor
public Cursor query(String table,String[] columns, String selection,String[] selectionArgs,String groupBy,String having,String orderBy){
return myDataBase.query("EMP_TABLE", null, null, null, null, null, null);

}
}
[/sourcecode]

Now you can create a new instance of this DataBaseHelper class in CopyDbActivity class and call the createDataBase() and openDataBase() methods. Remember to change the "YOUR_PACKAGE" to your application package namespace (i.e: com.mobisys.android.External_to_application) in the DB_PATH string or you can get package name using method context.getPackageName().

CopyDbActivity class contains:

[sourcecode language="xml"]
package com.mobisys.android.External_to_application;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CopyDbActivity extends Activity {
/** Called when the activity is first created. */
Cursor c=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

((Button)findViewById(R.id.button01)).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {

DatabaseHelper myDbHelper = new DatabaseHelper(CopyDbActivity.this);
try {

myDbHelper.createDataBase();

} catch (IOException ioe) {

throw new Error("Unable to create database");

}

try {

myDbHelper.openDataBase();

}catch(SQLException sqle){

throw sqle;

}
Toast.makeText(CopyDbActivity.this, "Success", Toast.LENGTH_SHORT).show();

c=myDbHelper.query("EMP_TABLE", null, null, null, null,null, null);
if(c.moveToFirst())
{
do {

Toast.makeText(CopyDbActivity.this,
"_id: " + c.getString(0) + "n" +
"E_NAME: " + c.getString(1) + "n" +
"E_AGE: " + c.getString(2) + "n" +
"E_DEPT: " + c.getString(3),
Toast.LENGTH_LONG).show();

} while (c.moveToNext());
}
}
});

}
}
[/sourcecode]
Run the Application.

Download the Source Code

Click here to download sourcecode.