In my application I have several persisted models and in one case I’m getting exception when trying to get data using corresponding getter. But there is data in tha DB and I have no idea why getter returns nothing.
Answer class:
@DatabaseTable
@JsonRootName(value = "answer")
public class Answer {
public Answer() {}
@DatabaseField(generatedId = true, columnName = "_id")
@JsonIgnore
private Integer id;
@DatabaseField
@JsonProperty(value = "id")
private Integer answer_id;
@DatabaseField(dataType = DataType.LONG_STRING)
private String text;
// some other fields and setters/getters
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
Question class:
@DatabaseTable
public class Question extends BaseDaoEnabled implements Serializable {
private static final long serialVersionUID = -7587892134579897L;
public Question() {
}
@DatabaseField(foreign = true, foreignAutoRefresh = true)
private Answer answer;
}
Quest class:
@DatabaseTable(tableName = "quests")
@JsonRootName(value = "quest")
public class Quest {
@DatabaseField(allowGeneratedIdInsert = true, generatedId = true, columnName = "_id")
private Integer id;
@DatabaseField(dataType = DataType.DATE_STRING)
Date created_at;
@DatabaseField(foreign = true)
private Survey survey;
@ForeignCollectionField(eager = false, orderColumnName = "question_id")
public Collection<Question> questions;
Answer creation:
answer.setText(input.getText().toString());
try {
if (answer.getId() == null) {
DBHelperFactory.GetHelper().getAnswersDao().create(answer);
question.setAnswer(answer);
DBHelperFactory.GetHelper().getQuestionsDao().update(question);
} else {
DBHelperFactory.GetHelper().getAnswersDao().update(answer);
}
Toast.makeText(this.getActivity(), "Answer saved", 5).show();
listener.nextQuestion();
} catch (SQLException e) {
Log.e(LOG_KEY, "Create failed", e);
}
And the failing code, (quest is passed in to the function that is running in the background)
for (Question question : quest.questions) {
if (question.getAnswer() != null) {
Log.d(LOG_KEY, question.getId().toString());
Log.d(LOG_KEY, question.getAnswer().getId().toString());
Log.d(LOG_KEY, question.getAnswer().getText());
// NullPointerException for getText().
}
}
getAnswer() indeed returns Answer. Data in DB persisted. But getText() is failing.
Can anyone please help me to find out where I am wrong?
The key was that
@DatabaseField(dataType = DataType.LONG_STRING)works strange and I couldn’t managed to make it work. After switching back toVARCHAR– problem dissappeared.