Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest and most efficient way to pre-populate database in Android

If you want to pre-populate a database (SQLite) in Android, this is not that easy as one might think.

So I found this tutorial which is often referenced here on Stack Overflow as well.

But I don't really like that way of pre-populating the database since you take the control from the database handler and create the files yourself. I would prefer to not touch the file system and let the database handler do everything on its own.

So what I thought one could do is create the database in the database handler's onCreate() as usual but then load a file (.sql) from /assets which contains the statements to fill in the values:

INSERT INTO testTable (name, pet) VALUES ('Mike', 'Tiger');
INSERT INTO testTable (name, pet) VALUES ('Tom', 'Cat');
...

But calling execSQL() in the handler's onCreate() doesn't really work. It seems that the /assets file must not have more than 1MB and the execSQL() only executes the first statement (Mike - Tiger).

What would you do do pre-populate the database?

like image 791
caw Avatar asked Jan 06 '12 01:01

caw


People also ask

Which database is best for Android?

PostgreSQL. A unique relational database, PostgreSQL is the best database for Android and iOS apps. Developers can customize this database as they want; that's why it's the most preferred mobile app database.

What is pre populated database?

Sometimes, you might want your app to start with a database that is already loaded with a specific set of data. This is called prepopulating a database.

Which database is pre installed with Android device?

SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.


1 Answers

I suggest the following:

  1. Wrap all of your INSERT logic into a transaction (BEGIN... COMMIT, or via the beginTransaction()... endTransaction() APIs)
  2. As already suggested, utilize the bind APIs and recycle objects.
  3. Don't create any indexes until after this bulk insert is complete.

Additionally take a look at Faster bulk inserts in sqlite3?

like image 66
NuSkooler Avatar answered Sep 28 '22 17:09

NuSkooler