1

I have a big JSON file in the assets and I want to store it in the DB using Room. Right now, my app takes the JSON file and parses it, generating some data models containing the information.

What is the way to insert it into the DB? Is the repository the one to do that? How do I know if the database is empty or that all that info has already been dumped into the DB?

Thanks in advance!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
noloman
  • 11,411
  • 20
  • 82
  • 129

1 Answers1

0

What is the way to insert it into the DB? Using an Insert query in your entity DAO, like:

@Insert
fun insertTickets(vararg tickets: Ticket)

Is the repository the one to do that? This is a matter of structure or your application. If you have a repository, then yes, the repository should be the one speaking with the database.

How do I know if the database is empty or that all that info has already been dumped into the DB? To know if the database is empty you would have to query all tables for data, either by issuing a Query with COUNT(*), like

@Query("SELECT COUNT(*) FROM X")
fun numberOfRecordsInX(): Long

or asking for any one row to see if something is returned. No idea which can be faster:

@Query("SELECT * FROM x ORDER BY rowid LIMIT 1")
fun gimmeAnyRowInX() : EntityX
Julen
  • 319
  • 2
  • 9
  • yes thanks for the answer. I have now populated the DB with a callback using `override fun onCreate(db: SupportSQLiteDatabase) `. But now, I have a problem: this is only done the first time the DB is accessed (which is when trying to retrieve the entity) and this means that the DB is populated but the query never returns. Is there any way to have a callback for when the DB is populated? or any other way to explicitedly initialize the DB first, and then retrieve the entity? – noloman Jan 12 '20 at 09:03
  • If your initialization data is static, that is, won't change over time, you can prepare a database with it, put is into the assets folder, and import it on build with `createFromAsset(ASSETS_DATABASE_NAME)`. If not, your method should work, the query should return. – Julen Jan 12 '20 at 09:41
  • thanks @Julen for the answer. Unfortunately no, it doesn't return because I see a retrieval query with 0 objects returning, and then the DB is prepopulated – noloman Jan 12 '20 at 10:11
  • I'll close this question and will open a new one because I think the original request is a bit different. Thanks! – noloman Jan 12 '20 at 10:57