Friday, 3 August 2012

Build an Android app using existing SQLite database

Step by step guide to use existing sqlite database file in Android application.



Step 1.
Prepare the SqLite database file

Step 2.
Create a table android_metadata in the database,
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
Insert a record as follows
INSERT INTO "android_metadata" VALUES ('en_US')
Step 3.
Rename primary Id fields of existing tables as _Id. So that Android will know where to bind the id field of your tables.

Now the database is ready.

Step 4.
Simply copy and paste the database.db file to 'assets' folder of the android project.

Step 5.
Create a class MyDatabaseAdapter to access the our own database through project.
It will extend from SQLiteOpenHelper class, which is in android.database.sqlite namespace.
MyDatabaseAdapter class look like this.

public class MyDatabaseAdapter extends SQLiteOpenHelper {

    private Context mycontext;

    private String DB_PATH = "data/data/texkpot.package.app/databases/";
//dont forget to change your namespace.package.app
    private static String DB_NAME = "database.db";
    // the extension may be .sqlite or db
    public SQLiteDatabase myDataBase;

    public DatabaseAdapter(Context context) {
        super(context, DB_NAME, null, 1);
        this.mycontext = context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            System.out.println("Database doesn't exist");
            try {
                createdatabase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkdatabase() {
        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            checkdb = dbfile.exists();
        } catch (SQLiteException e) {
            System.out.println("Database doesn't exist");
        }

        return checkdb;
    }

    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
        @SuppressWarnings("unused")
        String outfilename = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(
                "data/data/test.test.test/databases/test");

        // transfer byte to inputfile to 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 open() {
        // Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null,
                SQLiteDatabase.OPEN_READWRITE);

    }

    public synchronized void close() {
        myDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
}

thats it.

Step 6. 
Now we can create the instance of the MyDatabaseAdapter class to create and open the database.
The code will look like this


        DataBaseHelper myDbHelper = new DataBaseHelper();
        myDbHelper = new DataBaseHelper(this);
        try {
         myDbHelper.createDataBase();
  } catch (IOException ioe) {
  throw new Error("Unable to create database");
  }

  try {
  myDbHelper.openDataBase();
  }catch(SQLException ex){
  throw ex;
  }







3 comments:

Goutham said...

Awesome dude... great work keep the thing up...

Anonymous said...

is that work in android studio also ???

Guille Ortiz said...

how update the file or add one table, if is required?

Post a Comment