如何解决在Android RoomDB中使用KotlinFlow和删除数据时出现的错误?

bfrts1fy  于 2023-02-13  发布在  Kotlin
关注(0)|答案(1)|浏览(191)

删除RoomDB数据后出现以下错误:
java.lang.NullPointerException:尝试对空对象引用调用虚拟方法"java. lang. String app. zimablue. artbookfragmentversion. model. ArtEntity. getArtName()"
我想我得到这个错误是因为我试图再次访问已删除的数据,因为我可以删除数据,但我得到一个错误,因为没有数据将显示在屏幕上后,它被删除。

@Dao
interface ArtDao {

    @Insert
    suspend fun insert(artEntity: ArtEntity)

    @Delete
    suspend fun delete(artEntity: ArtEntity)

    @Query("SELECT * FROM `art-table`")
    fun getArtWithNameAndId():Flow<List<ArtEntity>>

    @Query("SELECT * FROM `art-table` WHERE id = :id")
    fun getArtById(id: Int): Flow<ArtEntity>
@Entity(tableName = "art-table")
class ArtEntity(

    @ColumnInfo(name = "name")
    @NonNull var artName : String,

    @NonNull @ColumnInfo(name = "artistname")
    var artistName: String,

    @NonNull @ColumnInfo(name = "year")
    var year : String,

    @NonNull @ColumnInfo(name = "image")
    var image : ByteArray

) {
    @PrimaryKey(autoGenerate = true)
    var id : Int = 0
}

错误指向的行。

private fun oldArtDetails(art : ArtEntity){
        artFromMain = art



        art.artName.let {
            binding.artText.setText(it)
        }
        art.artistName.let {
            binding.artistText.setText(it)
        }
        art.year.let {
            binding.yearText.setText(it)
        }
        art.image.let {
            val bitmap = it.let {
                BitmapFactory.decodeByteArray(it,0, it.size) }
            binding.imageView.setImageBitmap(bitmap)
        }

    }

我已经上传了发生错误的应用程序版本到Github:https://github.com/mertparlak-zima/ArtBookFragment
译文:我检查了"www.example.com"和"art.artistName"是否为空,但没有效果。我在数据库中使其可以为空,但仍然没有效果。art.name" and "art.artistName" are null, but it didn't work. I made it nullable in the database, but it still didn't work.

hgc7kmma

hgc7kmma1#

在ArtDao中,返回类型被设置为不可空,所以dao返回的ArtEntity实际上为空,但无法检查它是否为空。

    • 解决方案:**
@Query("SELECT * FROM `art-table` WHERE id = :id")
fun getArtById(id: Int): Flow<ArtEntity?>

相关问题