Robospice storing object that extends ArrayList in database via Ormlite

∥☆過路亽.° 提交于 2019-12-05 14:53:34

This question is not really a bug in RoboSpice, but a limitation of the ORM Lite model.

If you want to serialize a collection of Foo using ORMLite, then you must use serialize a class that is a collection of Foo. You approach is right. Nevertheless, you can't just get rid of it to store the Foo elements individually. You not only have to use the Foos class to parse the response but also to store data in the database.

Foos should :

  • define an id
  • be annotated using DataBaseTable and DataField and Foreign collection

The problem is that you can't annotate a class and saying "I am a Foreig Collection". This annotation can only be used on fields, not on classes. So If your class would "hold" a collection, that would work, but not for a class that "is a" collection.

So, I believe that the short answer is : no, you can't do that with ORM Lite. You must store a top class like Foos, but it should be serializable for ORM Lite and for this it needs to have a collection field, and can't be a collection directly.

To add on to this excellent question, I was also experiencing this 'silent failure' and did not know what to do. I eventually selected inside Android Studios to see all the messages in logcat, so not only the android errors, but everything. I did this by selecting "Verbose" and "No Filters".

When I ran my app, I discovered that the reason why I was getting a silent error was because I did not generate unique ID for my SQL and this caused it to bomb out.

 Caused by: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: post.ID (code 1555)

I fixed it by doing this on my outer class ID field which allowed it to generate unique IDs by itself:

@DatabaseField(allowGeneratedIdInsert=true, generatedId=true)
private int ID;
Uipko

As @Snicolas said, you should change to Collection instead of ArrayList. I wanted to do more or less the same but without the result object, my workaround on this question RoboSpice persist JSON array with OrmLite should work for you.

@DatabaseTable
public class Foos {
    @DatabaseField(id = true)
    private int id;
    @ForeignCollectionField(eager = false)
    private Collection<Foo> result;

    // getters and setters
    ...
}

@DatabaseTable
public class Foo {
    @DatabaseField(id = true)
    private int id;
    @DatabaseField(foreign = true)
    private Foos foos;

    // getters and setters
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!