Search code examples
androidkotlinandroid-room

How to set One to many relation in android room DB in kotlin


I have two tables. First table is as below

    @Entity
    data class GramPanchayatSurveyEntity(
    @PrimaryKey
    var gpCode: Int,
    var distCode: Int,
    var locationTypeCode: Int,
    var location: String,
    var latitude: String,
    var longitude: String,
    var googleLocation: String,
    var distanceBtwHeadQrToGp: String,
    var recommendedHeightOfTower: String,
    var BBNL_Exist: String,
    var anyCongestion: String,
    var nearByGpCode: Int,
    var surveyBy: String,
    var surveyAt: String,
    val status :String
)

And the second table as

@Entity
data class AddedPhotoEntity (
    @PrimaryKey
    var photoUniqueId:Int,
    var iPhotoTypeCode: Int,
    var photoTypeName: String,
    var sPhotoURL: String,
    var gpCode: Int,
    var photoStatus : String,
    var rotationAngle :Float
)

I have a relation class that fetches data from both tables as

class GpSurveyWithImageRelation {
     @Embedded
     var gpSurveyEntity: GramPanchayatSurveyEntity? = null

     @Relation(parentColumn = "gpCode", entityColumn = "gpCode")
     var sPhotoArray: List<AddedPhotoEntity>? = null
 }

When I am getting data from this relation and convert the data into JSON Array using gson it gives me the output like that

This is the actual output of when I convert the list (getting from the relation) into a JSON array

This is the required output.

Please anyone help me in creating the relation class between two tables so that I can got the required output.

Thanks in advance.


Solution

  • Your issue is that you have the var/field gpSurveyEntity Embedded as a GramPanchayatSurveyEntity object, instead you want GpSurveyWithImageRelation to be:-

    data class GpSurveyWithImageRelation(
        var gpCode: Int,
        var distCode: Int,
        var locationTypeCode: Int,
        var location: String,
        var latitude: String,
        var longitude: String,
        var googleLocation: String,
        var distanceBtwHeadQrToGp: String,
        var recommendedHeightOfTower: String,
        var BBNL_Exist: String,
        var anyCongestion: String,
        var nearByGpCode: Int,
        var surveyBy: String,
        var surveyAt: String,
        var status :String,
        @Relation(entity = AddedPhotoEntity::class, parentColumn = "gpCode", entityColumn = "gpCode")
        var sPhotoArray: List<AddedPhotoEntity> = emptyList()
    )