Adding Your Own SQLite Database to an Android Application

adding your own SQLite database to an android application

Try this code:

 public class DataBaseHelper extends SQLiteOpenHelper {
private Context mycontext;

//private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
private static String DB_NAME = "(datbasename).sqlite"; //the extension may be .sqlite or .db
public SQLiteDatabase myDataBase;
/*private String DB_PATH = "/data/data/"
+ mycontext.getApplicationContext().getPackageName()
+ "/databases/";*/

public DataBaseHelper(Context context) throws IOException {
super(context, DB_NAME, null, 1);
this.mycontext = context;
boolean dbexist = checkdatabase();
if (dbexist) {
//System.out.println("Database exists");
opendatabase();
} else {
System.out.println("Database doesn't exist");
createdatabase();
}

}

public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if (dbexist) {
//System.out.println(" Database exists.");
} else {
this.getReadableDatabase();
try {
copydatabase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkdatabase() {
//SQLiteDatabase checkdb = null;
boolean checkdb = false;
try {
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
//checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
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
String outfilename = DB_PATH + DB_NAME;

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

// 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 opendatabase() throws SQLException {
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);

}

public synchronized void close() {
if (myDataBase != null) {
myDataBase.close();
}
super.close();
}

Create or Install SQLite Database in Android Application

IT is possible.

Just create your SQLite database and place it in your asset folder.

When the app is first launched simply check whether or not the db exists and create it if doesn't exist.

    public String DB_PATH = null;
public final static String DB_NAME = "mye.db"; //take note this is in your asset folder
private static final int DB_VERSION = 1;
private SQLiteDatabase myDatabase;
private Context myContext = null;

public DBAdapter(Context context) {
super(context, DB_NAME, null, DB_VERSION);
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 {

this.getReadableDatabase();

try {
copyDatabase();
} catch (IOException e) {

throw new Error("Error copying database");

}
}

/**
* Copy DB from ASSETS
*/

public 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();
}

/**
* Opens Database . Method is synhcronized
* @throws SQLException
*/
public synchronized void openDatabase() throws SQLException {
String dbPath = DB_PATH + DB_NAME;
myDatabase = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READWRITE);
}

/**
* Closes database.
* Method is synchronized for protection
*/
@Override
public synchronized void close() {
if (myDatabase != null) {
myDatabase.close();
}
super.close();
}

/**
* Check if the database exists
*
* @param cntx
* @return true / false
*/
public boolean checkDatabase(Context cntx) {
File dbFile = cntx.getDatabasePath(DB_NAME);
// Log.e("zeus", "Check db returns : " + dbFile.exists());
return dbFile.exists();

}

In your main activity or class that extends application just get an instance to your DBAdapter and check if the db exists.

mDBAdapter = new DBAdapter(getApplicationContext());
if (!mDBAdapter.checkDatabase(getApplicationContext())) {
try {
mDBAdapter.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}

How to use an existing database with an Android application

NOTE:
Before trying this code, please find this line in the below code:

private static String DB_NAME ="YourDbName"; // Database name

DB_NAME here is the name of your database. It is assumed that you have a copy of the database in the assets folder, so for example, if your database name is ordersDB, then the value of DB_NAME will be ordersDB,

private static String DB_NAME ="ordersDB";

Keep the database in assets folder and then follow the below:

DataHelper class:

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

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {

private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
private static String DB_NAME ="YourDbName"; // Database name
private static int DB_VERSION = 1; // Database version
private final File DB_FILE;
private SQLiteDatabase mDataBase;
private final Context mContext;

public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_FILE = context.getDatabasePath(DB_NAME);
this.mContext = context;
}

public void createDataBase() throws IOException {
// If the database does not exist, copy it from the assets.
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist) {
this.getReadableDatabase();
this.close();
try {
// Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}

// Check that the database file exists in databases folder
private boolean checkDataBase() {
return DB_FILE.exists();
}

// Copy the database from assets
private void copyDataBase() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
OutputStream mOutput = new FileOutputStream(DB_FILE);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}

// Open the database, so we can query it
public boolean openDataBase() throws SQLException {
// Log.v("DB_PATH", DB_FILE.getAbsolutePath());
mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.CREATE_IF_NECESSARY);
// mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}

@Override
public synchronized void close() {
if(mDataBase != null) {
mDataBase.close();
}
super.close();
}

}

Write a DataAdapter class like:

import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TestAdapter {

protected static final String TAG = "DataAdapter";

private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;

public TestAdapter(Context context) {
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}

public TestAdapter createDatabase() throws SQLException {
try {
mDbHelper.createDataBase();
} catch (IOException mIOException) {
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}

public TestAdapter open() throws SQLException {
try {
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
} catch (SQLException mSQLException) {
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}

public void close() {
mDbHelper.close();
}

public Cursor getTestData() {
try {
String sql ="SELECT * FROM myTable";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur != null) {
mCur.moveToNext();
}
return mCur;
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
}

Now you can use it like:

TestAdapter mDbHelper = new TestAdapter(urContext);
mDbHelper.createDatabase();
mDbHelper.open();

Cursor testdata = mDbHelper.getTestData();

mDbHelper.close();

EDIT: Thanks to JDx

For Android 4.1 (Jelly Bean), change:

DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";

to:

DB_PATH = context.getApplicationInfo().dataDir + "/databases/";

in the DataHelper class, this code will work on Jelly Bean 4.2 multi-users.

EDIT: Instead of using hardcoded path, we can use

DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();

which will give us the full path to the database file and works on all Android versions

How use an external sqlite database in android application

using SQLiteAssetHelper (https://github.com/jgilfelt/android-sqlite-asset-helper) solved my problem!

How can I embed an SQLite database into an application?

I solved that problem by:

  1. adding file.db into project/assets folder;

  2. writing next class:

    public class LinnaeusDatabase extends SQLiteOpenHelper{

    private static String DATABASE_NAME = "Dragonfly.db";
    public final static String DATABASE_PATH = "/data/data/com.kan.linnaeus/databases/";
    private static final int DATABASE_VERSION = 1;

    private SQLiteDatabase dataBase;
    private final Context dbContext;

    public LinnaeusDatabase(Context context) {
    super(context, DBActivity.DatabaseName, null, DATABASE_VERSION);
    this.dbContext = context;
    DATABASE_NAME = DBActivity.DatabaseName;
    // checking database and open it if exists
    if (checkDataBase()) {
    openDataBase();
    } else
    {
    try {
    this.getReadableDatabase();
    copyDataBase();
    this.close();
    openDataBase();

    } catch (IOException e) {
    throw new Error("Error copying database");
    }
    Toast.makeText(context, "Initial database is created", Toast.LENGTH_LONG).show();
    }
    }

    private void copyDataBase() throws IOException{
    InputStream myInput = dbContext.getAssets().open(DATABASE_NAME);
    String outFileName = DATABASE_PATH + DATABASE_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);

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

    myOutput.flush();
    myOutput.close();
    myInput.close();
    }

    public void openDataBase() throws SQLException {
    String dbPath = DATABASE_PATH + DATABASE_NAME;
    dataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    boolean exist = false;
    try {
    String dbPath = DATABASE_PATH + DATABASE_NAME;
    checkDB = SQLiteDatabase.openDatabase(dbPath, null,
    SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
    Log.v("db log", "database does't exist");
    }

    if (checkDB != null) {
    exist = true;
    checkDB.close();
    }
    return exist;
    }
    }

Copy Sqlite database for android application

Using SQLiteAssetHelper solved the problem.



Related Topics



Leave a reply



Submit