j256 / ormlite-android

ORMLite Android functionality used in conjunction with ormlite-core
http://ormlite.com/
ISC License
1.59k stars 366 forks source link

"Could not find a field named ..." when calling getEmptyForeignCollection() #106

Closed regocziTamas closed 2 years ago

regocziTamas commented 5 years ago
@DatabaseField(generatedId = true, allowGeneratedIdInsert = true, columnName = "workout_block_id")
private Long id;

/*Field I am trying to add to*/
@ForeignCollectionField(columnName = "exercises")
private ForeignCollection<WorkoutExercise> exercises = null;

@ForeignCollectionField
private ForeignCollection<Rest> rests;

public void addComponent(WorkoutComponent component){
    if(exercises == null) {
        try {
            exercises = DatabaseHelper.getStaticWexDao().getEmptyForeignCollection("exercises");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if(component instanceof WorkoutExercise){
        exercises.add((WorkoutExercise) component);
    }else if(component instanceof Rest){
        rests.add((Rest) component);
    }
}`

I am having the following code, I am trying to initialize the "exercises" ForeignCollection with the getEmptyForeignCollection() method before adding elements to it, but it keeps throwing an IllegalArgumentException, saying that "Could not find a field named exercises", when I call the method. It doesn't work when I remove the columnName attribute either. What am I doing wrong? Thank you for the answer in advance!

androidworx commented 5 years ago

I suggest taking a look at the ORMLite foreign collection example program. The example has an "orders" ForeignCollection field in an "Account" class. The orders field is created when an Account is fetched from the database eg. Account accountResult = accountDao.queryForId(account.getId()); The orders are persisted to a separate "orders" database table and the ForeignCollection field is populated using a simple query which selects orders by Account id. It is possible to add items to a ForeignCollection field once it has been created by ORMLite and this is quite useful. However, the DAO getEmptyForeignCollection() call you are making does not work the way you expect and is not causing the ForeignCollection field to be created.

j256 commented 2 years ago

Sorry for the slow response. You've prolly moved on by now. Your example worked for me. My only guess is that maybe getStaticWexDao() wasn't returning the DAO you thought? Either that our maybe your table-config file had not been updated with the "exercises" field?