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
Using existing database to display data in Android app
set your data path directly as a string, hope it will work
private final static String DATABASE_PATH ="/data/data/com.yourpackagename/databases/";
public SQLiteDatabase openDatabase() throws SQLException
{ String myPath = DATABASE_PATH + "DB_NAME";myDataBase = SQLiteDatabase.openOrCreateDatabase(myPath, null, null);
return myDataBase;
}`
How to add data to existing database in my android app?
Why do you manually create path to your database? You should instead use your DatabaseHelper's getWritableDatabase()
and getReadableDatabase()
methods as it is explained in official manual. And write more detailed information why do you think it is not put into database, maybe you just can't read it correctly? Is there any error or crash? But first try to rewrite your code as it is given in official documentation.
How to insert existing DataBase in Android Project
Well, it's pretty easy, just put your database.db in assets folder and you can use Android SQLiteAssetHelper to read and write the database, this library makes the process pretty easy and straightforward.
Import the library
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
and then
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "northwind.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
That's all you need to do to access the database.
Here is the full example for your convenience.
placing existing sqlite database and reading
you should put it in the assets
folder.
This way you can make sure it will be attached to your apk.
this is how you can copy the database file from the assets folder to your working directory:
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();
}
now to read the database from the directory:
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
Access the existing database in new application
Just copy a database from assets
to file system (context.getFileDir()
for example).
EDIT
to access database in app 1 from app 2 you have 2 options:
1) create ContentProvider
in app 1 which give access to data in database. This is the best solution because you can manage access to this data using permissions. Look this for more details
2) store database file on sd_card (using external file dir and so on). In this case any application have access to your database.
3) use the same certificate for both application. in this case android create the same user for both apps and they will have access to files in each other.
I suggest you to use the first solution
Related Topics
How to Check Internet Access on Android? Inetaddress Never Times Out
Java.Text.Parseexception: Unparseable Date: Java.Text.Dateformat.Parse(Dateformat.Java:579)
Android: Internet Connectivity Change Listener
Java Command Not Found on Linux
Sort a Map≪Key, Value≫ by Values
Loop Doesn't See Value Changed by Other Thread Without a Print Statement
What Is the Volatile Keyword Useful For
Java: Maintaining Aspect Ratio of Jpanel Background Image
Using Jfreechart to Display Recent Changes in a Time Series
Setting Singleton Property Value in Firebase Listener
Com.Android.Build.Transform.API.Transformexception
Parsing Query Strings on Android
Limit Jvm Process Memory on Ubuntu
Swing Gui Listeners Without Awt
How to Add Local Jar Files to a Maven Project
How to Download and Save a File from the Internet Using Java