Pre-load database in app

To provide data in the apk in the form of a database it must be done in 2 stages:

  • create your database and table and copy the file into the app
  • write code in your app to copy that file into a form it can use.

My thanks to the authors of these 2 pages that I used to understand this and get it working: mobisys and xatik.

Create database

Simplest way to create sqlite database: download Firefox then download the SQLite Manager add-on. Start Firefox, show main menu and SQLite Manager is under Tools.

To be understood by Android there are 2 requirements:

  • you must have an android_metadata table
  • the column name of the primary key of your table must be _id.

Create a new table (right click on tables) and enter the following:

table name android_metadata
column name locale
data type text
primary key, allow null & unique all not checked
default en_us

Insert a row: go to the Execute SQL table, enter ‘INSERT INTO “android_metadata” VALUES (‘en_US’)’ (without outside quotes) and click Run SQL.

Create your own table and insert data. For example:

CREATE TABLE Currencies(_id INTEGER PRIMARY KEY autoincrement, Country text not null, Currency text not null, Code char not null)
INSERT INTO Currencies (Country, Currency, Code) VALUES (‘Albania’,’Albanian Lek’,’ALL’)

Exit SQLite Manager, import the file into the assets folder of your app and then rename it to remove the extension.

Code to copy and use database

As a simple demo, put a button on the layout of your main activity.

 

<?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>

Create a helper class that extends SQLiteOpenHelper.

 

package couk.jit.databasetestcurrencies;

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;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
	//The Android's default system path of your application database.
    String DB_PATH =null;
     private static String DB_NAME = "CurrCheck1";
     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 {
                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[1024];
        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("CURRENCIES", null, null, null, null, null, null);
    }
}

Code your main activity to initiate the copy and read the data.

 

package couk.jit.databasetestcurrencies;

import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */
	Cursor c = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

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

						DatabaseHelper myDbHelper = new DatabaseHelper(
								MainActivity.this);
						try {
							myDbHelper.createDataBase();

						} catch (IOException ioe) {

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

						}

						try {

							myDbHelper.openDataBase();

						} catch (SQLException sqle) {

							throw sqle;

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

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

								Toast.makeText(
										MainActivity.this,
										"_id: " + c.getString(0) + "\n"
												+ "Country: " + c.getString(1)
												+ "Currency: " + c.getString(2)
												+ "Code: " + c.getString(3),
										Toast.LENGTH_LONG).show();

							} while (c.moveToNext());
						}

					}
				});

	}
}

Run your app and click the button. The toast messages should declare success and then display your data.

I initially had problems with my db_name but tackling this was complicated by the fact that, even though the db copy failed, part of the background work had been completed. So running the app a second time gives a different error message, even if you’ve made no code changes (and potentially more confusing if you have!). Once I realised this and uninstalled the app before each code change, the problem was quickly fixed.

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *