Problems saving collection using ORMLite on Android

I have two classes:

public class Questionnaire { @DatabaseField(generatedId=true, useGetSet=true) private Long id; @DatabaseField private int type; @DatabaseField private String title; @DatabaseField private String description; @ForeignCollectionField(eager = true) private Collection<Question> questions; // Get and Set omitted 

and

  public class Question { @DatabaseField(generatedId=true, useGetSet=true) private Long id; @DatabaseField private int type; @DatabaseField private String description; @DatabaseField(foreign = true, foreignAutoRefresh= true) private Questionnaire questionario; //get and set ommited 

When I save a questionnaire with a list of questions. Objects are saved, but I'm losing touch.

I save this way:

 ForeignCollection<Question> questions = getDao(Questionnaire.class).getEmptyForeignCollection("questions"); for(Question question : DataUtil.getAllQuestions()) { questions.add(question); } Questionnaire questionnarie = new Questionnaire(); questionnarie.setQuestions(questions); questionnarie.setTitle("Normal"); questionnarie.setDescription("Questionário normal"); getDao(Questionnaire.class).createOrUpdate(questionarie); 

When I received this register from the database, the Question data does not have a link for Questionnaire , and my Questionnaire not filled with a completed list of questions.

Any help would be appreciated.

+4
source share
1 answer

The problem is that you are not setting the questionario field to Question objects. The relationship is from Question to associated Questionnaire . There is nothing in the Questionnaire table, which points to a different path. See Foreign Objects Documentation.

I would recommend doing something like the following:

 Dao<Questionnaire, Long> dao = getDao(Questionnaire.class); ForeignCollection<Question> questions = dao.getEmptyForeignCollection("questions"); Questionnaire questionnarie = new Questionnaire(); questionnarie.setQuestions(questions); questionnarie.setTitle("Normal"); questionnarie.setDescription("Questionário normal"); dao.createOrUpdate(questionarie); for(Question question : DataUtil.getAllQuestions()) { // you must set the questionnarie field on the Question // if it is a generated-id, it must be set _after_ it has been created question.setQuestionnaire(questionnarie); questions.add(question); } 
+17
source

Source: https://habr.com/ru/post/1439677/


All Articles