2

Im facing some problems while im trying to import an existing SQL Database into my project . I located the .db file in src/assets folder , and configured my DBHandler like this:

public class DatabaseOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "test.db";
private static final int DATABASE_VERSION = 1;

public DatabaseOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

But , whenever I try to make a raw query from a table, Android , instead of use the database from my assets folder , creates a empty new one with the same name and a table called android_metadata only.

How can I setup this correctly?

Gustavo Pagani
  • 6,583
  • 5
  • 40
  • 71
Nexussim Lements
  • 535
  • 1
  • 15
  • 47

1 Answers1

2

In essence you need to copy the file from the assets folder to a usable location, typically data/data/your_packagae/databases/test.db.

The code you have provided will, as you have found, not even consider the file that is in the assets folder and thus upon the first attempt to open the database (when you first access it as no attempt is made to open the database when you instantiate the DatabaseOpenHelper object), a new empty database with no tables (bar the android_metadata table, which is created as part of the open by the android SDK).

The copy of the file should only be done if the file doesn't exist in that location.

You could simplify the copy over by using the SQLiteAssetHelper, noting that this requires that the file to be copied is located in the databases directory of the assets folder (you may have to create the databases directory).

Alternately you could use your own copy process, this answer is an example (albeit it a bit bloated for demonstration/explanation) that does this.

MikeT
  • 51,415
  • 16
  • 49
  • 68