Been struggling with this all day. I feel like I am one annotation away from the right solution.
I am getting an JSON from an API, and parsing it using Gson inside Volley request into a object. Then I want to store the object in DB, using ORMLite.
The problem is that my JSON has lists of other objects. So I have decided that ForeignCollection are required.
Here is simplified version of what I am getting as JSON:
{
"b": [
{"title"="abc","id="24sfs"},
{"title"="def", "id="532df"}
],
"c": [
{"description"="abc","id="34325"},
{"description"="def", "id="34321"}
],
"id"="ejsa"
}
Lets call this whole object class A. The objects inside "b", are B, inside "c", class C.
B and C are the similar. This leads to the following class definitions:
class A {
@DatabaseField(index = true, unique = true, id = true)
private String id;
@ForeignCollectionField(eager = true)
public Collection<B> bCollection;
public ArrayList<B> b;
@ForeignCollectionField(eager = true)
public Collection<C> cCollection;
public ArrayList<C> c;
}
class B {
@DatabaseField(foreign=true)
public A a;
@DatabaseField(id = true, index = true, unique = true)
public String id;
@DatabaseField
public String title;
}
The reason we need the ArrayList b and c, is so that gson can parse it correctly. So once I have class A in memory, here is what I do to store it
private void storeA(A a) {
if (a.b != null) {
getHelper().getDao(B.class).callBatchTasks(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (B b : a.b) {
b.a = a;
try {
getHelper().getDao(B.class).createOrUpdate(b);
} catch (Exception e) {
}
}
return null;
}
});
}
/*
Here we start running into problems. I need to move the data from the ArrayList to the Collection
*/
a.bCollection = a.b; // but this seems to work, since bCollection is a Collection
a.cCollection = a.c;
getHelper().getDao(A.class).createOrUpdate(a);
}
So it seems to store correctly, no errors as far as I can tell. But when I try to retrieve as follows, I can't retrieve anything out of bCollection:
private void load() {
try {
List<A> as = getHelper().getDao(A.class).queryForEq("id", "ejsa");
if (as != null && as.size() > 0) {
A a = as.get(0);
CloseableWrappedIterable<B> cwi = a.bCollection.getWrappedIterable();
try {
for (B b : cwi) {
Log.e(b.title);
}
} finally {
cwi.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
What am I doing wrong? Do I need to specify foreignColumnName for some of these things? I can't tell if the things are not being stored correctly or if I am just failing to retrieve them correctly?
I would try removing the following two lines:
a.bCollection = a.b;
a.cCollection = a.c;
A's ForeignCollection
's should be auto-magically populated for you by ORMLite when you query for A, you do not need to set them yourself.