如何解决“实体和Pojos必须具有可用的公共构造函数”错误?

时间:2019-04-25 04:06:35

标签: java android android-room

我正在尝试在Android应用程序中设置Room。我收到此错误,但我真的不明白为什么。

完全错误:实体和Pojos必须具有可用的公共构造函数。您可以有一个空的构造函数或一个其参数与字段匹配的构造函数(按名称和类型)。

我正在使用1.1.1版的Room。我尝试了空的构造函数,使用了params的构造函数,还修复了我所有的警告,以致没有其他问题。

这是我的实体:

标记实体

@Entity(tableName = "markers")
public class Marker {
    public Marker(@Nullable String title, @Nullable String snippet, String latitude, String longitude, float color) {
        this.title = title;
        this.snippet = snippet;
        this.latitude = latitude;
        this.longitude = longitude;
        this.color = color;
    }

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String title;
    private String snippet;
    private String latitude;
    private String longitude;
    private float color;

    /* Getters and setters */
}

照片实体

@Entity(tableName = "photos",
        foreignKeys = @ForeignKey(entity = Marker.class,
                                  parentColumns = "id",
                                  childColumns = "marker_id"),
        indices = {@Index("marker_id")})
public class Photo {
    public Photo(String imageBase64, int markerId) {
        this.imageBase64 = imageBase64;
        this.markerId = markerId;
    }

    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "image")
    private String imageBase64;

    @ColumnInfo(name = "marker_id")
    private int markerId;

    /* Getters and setters */
}

网络实体

@Entity(tableName = "networks",
        foreignKeys = @ForeignKey(entity = Marker.class,
                                  parentColumns = "id",
                                  childColumns = "marker_id"),
        indices = {@Index("marker_id")})
public class Network {
    public Network(String ssid, String bssid, String capabilities, long timestamp, int markerId) {
        this.ssid = ssid;
        this.bssid = bssid;
        this.capabilities = capabilities;
        this.timestamp = timestamp;
        this.markerId = markerId;
    }

    @PrimaryKey(autoGenerate = true)
    private int id;

    private String ssid;
    private String bssid;
    private String capabilities;
    private long timestamp;

    @ColumnInfo(name = "marker_id")
    private int markerId;

    /* Getters and setters */
}

这是我在build.gradle文件中对Room的依赖关系:

def room_version = "1.1.1"

implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"

我看着很多这样的问题,但没有一个能解决我的问题。

2 个答案:

答案 0 :(得分:1)

像这样创建空的构造函数。

public Marker(){};

public Photo(){};

public Network(){};

或者您可以删除所有构造函数。清理项目并重建。检查是否可行。

答案 1 :(得分:0)

该错误是由于MarkerDao类中的错误而不是实体本身(某种程度上)引起的。

更准确地说,一个函数试图从LatLng查询中获取SELECT string, string from ...对象:

@Query("SELECT latitude, longitude FROM markers WHERE id = :id")
LatLng getMarkerLatitude(int id);

此错误非常烦人,因为它没有提供详细信息。如果有人发现此问题,请注释掉您的实体和DAO,并一次取消注释,以查看错误从何处开始。

祝你好运!

来源:我与@ Jean-Christophe Martel合作