1

I'm trying to populate my ROOM database with a simple JSON that I have inside the raw folder, this is my code

fun getInstance(context: Context): CarDatabase {
    if(instance == null) {
        instance =  Room.databaseBuilder (
            context,
            CarDatabase::class.java, "cars_table"
        ).createFromAsset("app/res/raw/cars_sample.json").build()
    }
    return instance as CarDatabase
}

And I get this

Caused by: java.io.FileNotFoundException: app/res/raw/cars_sample.json

AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
SNM
  • 5,625
  • 9
  • 28
  • 77

1 Answers1

0

Unless your module has src/main/assets/app/res/raw/cars_sample.json, that is not a valid path within assets/ to your JSON. And, since Android cannot find that JSON, my guess is your module does not have that asset.

From the looks of what you are using, my guess is that you are trying to populate your database from a raw resource. Raw resources are similar to assets, but they are not assets.

You will need to create an assets/ directory for your module and move your JSON there.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Hi, thanks for the answer, but I think I cannot move the json to assets because my requirement is to populate my database from the raw resource folder, is there any way of doing it ? – SNM Sep 18 '21 at 18:51
  • @SNM: You could try using `openRawResource()` on `Resources` to get an `InputStream` and use that [with `createFromInputStream()` on `RoomDatabase.Builder`](https://developer.android.com/reference/androidx/room/RoomDatabase.Builder#createFromInputStream(java.util.concurrent.Callable%3Cjava.io.InputStream%3E)). I have not tried that though. – CommonsWare Sep 18 '21 at 19:01