Store object created by gson in greenDao

Asked by At

Issue: I'm not able to insert a gson created object without id into the database using greenDao

Setup GreenDao

My web service returns an output like this

[
    {
        id: 2,
        firstName: "John",
        lastName: "Cleese",
        dateOfBirth: -952473600,
        profession: {
            name: "Actor",
            description: "TV show entertainer"
        }
    }
]

Gson turns this into a Person object that has a Profession object. These classes where generated using the GreenDao Generator.

Schema schema = new Schema(SCHEMA_VERSION, "com.example.dao");

Entity profession = schema.addEntity("Profession");
profession.addIdProperty().autoincrement().notNull();
profession.addStringProperty("name");
profession.addStringProperty("description");

Entity person = schema.addEntity("Person");
person.addIdProperty();
person.addStringProperty("firstName");
person.addStringProperty("lastName");
person.addDateProperty("dateOfBirth");
Property professionProperty = person.addLongProperty("profession_id").getProperty();
person.addToOne(profession, professionProperty);

new DaoGenerator().generateAll(schema, "my/path/java");

Insert issue:

Now I'm trying to insert the created Person object and its Profession object like this:

DaoMaster master = new DaoMaster(devOpenHelper.getWritableDatabase());
    DaoSession session = master.newSession();
    PersonDao personDao = session.getPersonDao();
    List<Person> people = myWebServiceResponse.getPeople();
    ProfessionDao professionDao = session.getProfessionDao();
    personDao.insertOrReplaceInTx(people);
    for (Person person : people) {
        try {
            professionDao.insertInTx(person.getProfession());
        } catch (Exception e) {
            Log.e("MainActivity", "Issue on insert: " + e.getMessage());
        }
    }

The person.getProfession() throws this exception: Attempt to invoke virtual method 'long com.example.dao.Profession.getId()' on a null object reference

If I turn things around, by inserting the Profession first and then the Person objects, it throws Entity is detached from DAO context on the same person.getProfession() call

1 Answers

4
Jofre Mateu On Best Solutions

I'm afraid that GreenDao and Gson are not a friendly couple. This is because in GreenDao, all the entities must be inserted before the object construction.

In this case, Profession is not a field, it's a relation, so when you do person.getProfession() you are retrieving this value from the Profession table, not from the Person object. You should insert both Person and Profession objects and establish their relation afterwards.

It's really an inconvenient that this two tools doesn't work well together, but as far as I know, it's how it works.