向 Room 数据库插入对象的空指针异常

问题描述 投票:0回答:0

当我将一个对象保存到房间数据库时,我得到了一个非常奇怪的空指针。没有一个实际参数为空。这是导致空指针的代码。

   if (it?.poster != null)  {
           insertPoster(it.poster)
      }

这里是数据库插入语句

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertPoster(poster: Poster)

这里是'it'的计算结果,所以被插入的对象是 it.poster

PosterWithWorker(poster=Poster(poster_id=4, job_id_map=3, qr_code=code5, worker_id=0, latitude=43.63904362027761, longitude=-79.38193214610098, locationDescription=Harbourfront), worker=null)

这是错误。

Failure(java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.Collection.isEmpty()' on a null object reference)

所有这些都在挂起函数中运行我认为可能存在一些竞争条件或使用调试器引起的问题。无论如何,我们将不胜感激任何意见或建议,感谢您阅读我的帖子!

这里是实体

package com.davidozersky.posterpal.database.entities

import androidx.room.*
import com.fasterxml.jackson.annotation.JsonProperty

@Entity(
    foreignKeys = [
        ForeignKey(
            entity = Job::class,
            parentColumns = ["job_id"],
            childColumns = ["job_id_map"],
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        )
    ]
)
data class Poster (
    @JsonProperty("poster_id")
    @PrimaryKey val poster_id: Long,
    @ColumnInfo(index = true)
    @JsonProperty("job_id_map")
    val job_id_map: Long,
    @JsonProperty("qr_code")
    val qr_code: String,
    @JsonProperty("worker_id")
    val worker_id: Long,
    @JsonProperty("latitude")
    val latitude: Double,
    @JsonProperty("longitude")
    val longitude: Double,
    @JsonProperty("locationDescription")
    val locationDescription: String,
    )
data class PosterWithWorker(

    @JsonProperty("poster")
    @Embedded val poster: Poster,
    @Relation(
        parentColumn = "worker_id",
        entityColumn = "worker_id",
        associateBy = Junction(
            value = PosterWorkerCrossRef::class,
            parentColumn = "poster_id_map",
            entityColumn = "worker_id_map"
        )
    )
    @JsonProperty("worker")
    val worker:  List<Worker>
) : Serializable

添加一些空指针检查后,我没有看到空指针错误。添加空指针检查后我可能没有重建。我仍然无法将工人和海报保存到数据库中。当我得到这些项目时,列表是空的。

android nullpointerexception android-room
© www.soinside.com 2019 - 2024. All rights reserved.