Search code examples
androidarrayssqliteandroid-roomandroid-architecture-components

Room; Store integer array to a separate table?


Using Room ORM, I have declared an entity EQPreset using @Entity annotation. The entity contains an array int[]. It gives following error:

error: Cannot figure out how to save this field (int[] arr) into database. You can consider adding a type converter for it.

Normally saving EQPreset instance to a database, I would create a separate table to store values of the array and have a foreign key pointing to the relevant EQPreset.
However, I need to find what will be the way of storing this int[] arr of EQPreset using Room, that is, either by making a separate table or using any good approach/way.


Solution

  • Option #1: Get rid of int[] arr. Have some other entity represent this integer, with a foreign key back to the EQPreset entity. Have methods on your DAO be able to give you the integer-entities for a given EQPreset entity.

    Option #2: Use a @TypeConverter to convert the int[] into something that can go into a single column (e.g., convert it to and from a JSON array, represented as a string).