2

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?

Farbod Salamat-Zadeh
  • 19,687
  • 20
  • 75
  • 125
Thomas
  • 51
  • 4
  • Put in assets folder in your app. check this - http://stackoverflow.com/questions/9109438/how-to-use-an-existing-database-with-an-android-application – Wasim K. Memon May 10 '16 at 10:03

3 Answers3

1

enter image description here

You have to add it into asset folder and reference it back in helper class

Haroon
  • 497
  • 4
  • 13
1

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Atiq
  • 14,435
  • 6
  • 54
  • 69
  • Thank you! If I decide to use SQLiteAssetHelper will I also be able to write on the DB ? – Thomas May 11 '16 at 11:01
  • yup ofc, you can use `getWritableDatabase()` with asset helper to write any values to database – Atiq May 11 '16 at 11:04
0

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

}
Vanraj Ghed
  • 1,261
  • 11
  • 23