How do I create an SQLite database in Android by importing from an SQL file?
I had to solve the same problem. Couldn't find a direct way to do it, so I put the file into the res/raw directory and used openRawResource
to get an InputStream on it. I then read lines until one ended with a ;
. I then passed the statement to the sqlite database.
Hopefully someone else comes along with a better way, but I thought I would just add the way that I ended up doing it.
Following Steve Prentice's answer. That's my implementation:
mydb.sql file in res/raw
CREATE TABLE table1(col1 INTEGER PRIMARY KEY, col2 TEXT);CREATE TABLE table2(col1 INTEGER PRIMARY KEY, col2 TEXT, col3 INTEGER);
MyClass.java
InputStream inputStream = context.getResources().openRawResource(R.raw.mydb); String queries = ""; try { queries = IOUtils.toString(inputStream); } catch (IOException e) { Util.logException(e); } for (String query : queries.split(";")) { db.execSQL(query); }
In the SQLiteOpenHelper onCreate() method you can just use db.execSQL(...)
but that depends on how your 'text file' is structured (and how big it is).
Alternatively, you can 'ship' a SQLite db with your app - see this link to give you some ideas...