I would like to insert an existing SQLite database into my Android project.
In other words, I do not want to create it, but just to be able to access it within my app.
How would I be able to access the database, and in which folder should I put it?
I would like to insert an existing SQLite database into my Android project.
In other words, I do not want to create it, but just to be able to access it within my app.
How would I be able to access the database, and in which folder should I put it?
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.
Put Your Data Base In Asset Folder
public void CopyDataBaseFromAsset() throws IOException {
InputStream in = context.getAssets().open(DATABASE_NAME);
Log.e("sample", "Starting copying");
String outputFileName = DATABASE_PATH+DATABASE_NAME;
File databaseFile = new File( "/data/data/*YOUR PACKGE NAME*/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0){
out.write(buffer,0,length);
}
Log.e("sample", "Completed" );
out.flush();
out.close();
in.close();
}