Search code examples
androidandroid-sqliteormliteprimitive-typesforeign-collection

how to store a collection of primitive type (String) into database


I'm trying to map my classes to the SQLite database using ORMLite and i have trouble to store a collection of String i have this error :

java.lang.IllegalArgumentException: No fields have a DatabaseField annotation in
     class java.lang.String

this error is self explanatory but how i do to store a collection of strings should i extend String class and add the annotations needed in order to do that ? in the annotation of the field i added datatype.serializable but that too wouldn't work. here's my class where i have the problem :

@DatabaseTable(tableName = "parameters")

public class Parameters {

    // id is generated by the database and set on the object automagically
    @DatabaseField(generatedId = true)
    int id_parameters;

    @DatabaseField(canBeNull = true)
    @JsonProperty("id")
    private Integer id;

    @DatabaseField(canBeNull = false)
    @JsonProperty("account_id")
    private Integer account_id;

    @ForeignCollectionField
    @JsonProperty("languages")
    private Collection<String> languages;
    ...
}

the field in question is languages!


Solution

  • Yeah, you can't just do a collection of strings. You will need to create a wrapper class with a String field in it as well as a foreign Parameters field:

    public class Language {
        @DatabaseField(generatedId = true)
        int id;
        @DatabaseField
        String language;
        @DatabaseField(foreign = true)
        Parameters parameters;
    }
    

    Here's the description of foreign collections from the FM. To quote:

    Remember that when you have a ForeignCollection field, the class in the collection must (in this example Order) must have a foreign field for the class that has the collection (in this example Account). If Account has a foreign collection of Orders, then Order must have an Account foreign field. It is required so ORMLite can find the orders that match a particular account.