Most of the tutorials found on the web assumes that you want to create and populate your own SQlite database at run time and use it in your application. But there are cases when you would like to use your own existing SQLite database in android application.
In this article, I will provide you a step by step guide to use your own SQLite database in android applications. The SQlite database should be kept in the "assets" folder of your application and this databse needs to be copied in the system database path of the application. This will enable the application to open and access it normally using the SQLiteDatabase API of android.
Step 1 : Preparing the SQlite Database File
In order to use the SQLite database in Android, some minor modifications are requried. You can use any opensource SQLite Database Browser or sqlite manager for this purpose.
Add a new table to your database "android_metadata" using the following SQL command:
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
Now add a single row in this table with text "en_US" in the android_metadata table.
INSERT INTO "android_metadata" VALUES('en_US')
The next important step is to rename all the primary fields of your table to "_id" . This helps Android bind the id fields of your tables.
Renaming of the primary field can be easily done by pressing the "Modify Table" button in SQlite Database Browser and then choosing the field you want to rename.
Once the above steps are done, your database is ready to use in your application.
Step 2: Using the Sqlite Database in Android Application
Copy the sqlite database file in "assets" folder and create a DatabaseHelper class by extending the SQLiteOpenHelper class from the "android.database.sqlite" package.
The DatabaseHelper class should look like this:
In this article, I will provide you a step by step guide to use your own SQLite database in android applications. The SQlite database should be kept in the "assets" folder of your application and this databse needs to be copied in the system database path of the application. This will enable the application to open and access it normally using the SQLiteDatabase API of android.
Step 1 : Preparing the SQlite Database File
In order to use the SQLite database in Android, some minor modifications are requried. You can use any opensource SQLite Database Browser or sqlite manager for this purpose.
Add a new table to your database "android_metadata" using the following SQL command:
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
Now add a single row in this table with text "en_US" in the android_metadata table.
INSERT INTO "android_metadata" VALUES('en_US')
The next important step is to rename all the primary fields of your table to "_id" . This helps Android bind the id fields of your tables.
| Rename Primary Field of your sqlite tables to _id |
Once the above steps are done, your database is ready to use in your application.
Step 2: Using the Sqlite Database in Android Application
Copy the sqlite database file in "assets" folder and create a DatabaseHelper class by extending the SQLiteOpenHelper class from the "android.database.sqlite" package.
The DatabaseHelper class should look like this:
package com.da.db;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
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.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;
//http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
public class DatabaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
//YOUR_PACKAGE should be replaced by your package name e.g. com.da
private static String DB_NAME = "da.db";;
private SQLiteDatabase myDataBase;
private final Context myContext;
private Cursor favCursor = null;
private final static int version = 1;
/**
* 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, version);
this.myContext = context;
}
/**
* 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
*/
public 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 deleteDataBase()
{
boolean exists = checkDataBase();
if(exists)
{
//delete
File file = new File(DB_PATH + DB_NAME);
file.delete();
}
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void openDataBase(int mode) throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, mode);
}
@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) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
private static String DB_NAME = "da.db";;
private SQLiteDatabase myDataBase;
private final Context myContext;
private Cursor favCursor = null;
private final static int version = 1;
/**
* 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, version);
this.myContext = context;
}
/**
* 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
*/
public 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 deleteDataBase()
{
boolean exists = checkDataBase();
if(exists)
{
//delete
File file = new File(DB_PATH + DB_NAME);
file.delete();
}
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void openDataBase(int mode) throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, mode);
}
@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) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
Now your database is ready for use. Just create an instance of this DataBaseHelper class and call its createDataBase() and openDataBase() methods.
Point to Remember : Make sure you rename the YOUR_PACKAGE in DB_PATH to your application packge e.g. com.da
...
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 sqle){
throw sqle;
}
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
} try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
No comments:
Post a Comment