简体   繁体   中英

How to use entity class which extends another class in a Room?

I tried searching everything but i didn't find any solution. One question is similar but no one has answered it properly. Moving to the question, I have a class which has room entity annotation and the same class extends another class (which is Library class). Now when i run the project I get an errors like Error:Cannot find getter for field. Library's super class making issue here as it works when i remove it. Please tell me how can i make room work with subclass as entity extending super class. Thank you for your time.

    @Entity(tableName = "event")
public class EventDetails extends ParentEntity implements Parcelable{

    @PrimaryKey(autoGenerate = true)
    int id;

    String name;
    Calendar startDay = Calendar.getInstance();
    Calendar endDay = Calendar.getInstance();

public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Calendar getStartDay() {
        return startDay;
    }

    public void setStartDay(Calendar startDay) {
        this.startDay = startDay;
    }

    public Calendar getEndDay() {
        return endDay;
    }

    public void setEndDay(Calendar endDay) {
        this.endDay = endDay;
    }

public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}



public class ParentEntity {
    private Calendar mDay;


    public Calendar getmDay() {
        return mDay;
    }

    public void setmDay(Calendar mDay) {
        this.mDay = mDay;
    }

}

This seems to be mainly a naming problem: after changing the field name from mDay to just day and renaming the setter/ getter accordingly, everything compiles.

It looks like the method names which Android Studio generates from mDay are not the ones which Room is looking for.

Since you are in a position to use different field names in the parent class, this looks like the best solution.

If it is not possible to change the library, it is especially not possible to mark fields in the library class with Ignore , so one can't fix the problem by inserting an intermediate class into the inheritance hierarchy. (I tried using a Constructor for EventDetails with the private field as argument but this too did not work)

So in this case I think your best option would be not to try to extend from the library class (but maybe from some "surrogate parent" class) and to bridge the gap to the library class with the help of some factory class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM