jrh
jrh

Reputation: 764

android ormlite - storing string array

I want to persist a class which contain String array. How to do it in ormlite? For example,

class A {
    int age;
    String[] childrenNames = new String[2];
}

Upvotes: 4

Views: 5868

Answers (3)

lucasddaniel
lucasddaniel

Reputation: 1789

@Gray told the better way todo.

@ForeignCollectionField(eager = false) ForeignCollection orders;

From docs: In the above example, the @ForeignCollectionField annotation marks that the orders field is a collection of the orders that match the account.

The field type of orders must be either ForeignCollection or Collection – no other collections are supported because they are much heavier with many methods to support.

Upvotes: 2

Gray
Gray

Reputation: 116888

I want to persist a class which contain String array. How to do it in ormlite? For example,

You could store this as a serialized stream for sure.

However, a better way to do this is to use a ForeignCollection. ORMLite does not do the magic fu that other ORM libraries do to support arrays. Maybe it should. In the meantime, here are the docs on setting up another table for your children-names:

http://ormlite.com/docs/foreign-collection

One table would be for A. Another table would be for the ChildrenName. Each ChildrenName entity would have a foreign-field of A which would show which A each name corresponded to.

Upvotes: 3

nikitanl
nikitanl

Reputation: 197

First you make the class Serializable. You can optionally add the table name at the top of the class by annotation.

then for the variables you have to add the database field annotation. In case of the string array you also have to annotate it as a Serializable datatype. You will get something like this:

@DatabaseTable(tableName = "A")
Class A implements Serializable{

    @DatabaseField
    int age

    @DatabaseField(dataType = DataType.SERIALIZABLE)
    String[] childrenNames = new String[2];
}

Also dont forget to create getters and setters for each of the variables.

Upvotes: 10

Related Questions