Kotlin:刚刚从roomdatabase中获得了第一个参数

问题描述

我的代码有问题,我无法解决。 让我简要介绍我要做的事情:我在ChooseFragment中有一个地址,还有一个用于编辑地址的编辑按钮。好的到目前为止很好。编辑单击是将新地址传递给DatabaseRoom,并且地址文本将被更改。但这只是第一次。第二时间地址没有改变! 。我知道insert方法可以工作并将新数据发送到数据库室,但是当我想通过查询(SELECT * FROM ...)获取它时,只需显示一个参数,而不用新值替换即可。我的代码有什么问题?

这是我的桌子:

const

这是我的数据库

@Entity (tableName = "addresstable")
data class Addresstb(

    @PrimaryKey(autoGenerate = true)```
    val id : Int?,var address: String)```

这是我的存储库:

@Database(entities = [RoomTables::class,Addresstb::class],version = 1,exportSchema = false)


abstract class DataBaseRoom : RoomDatabase() {

    abstract fun GetDao(): DaoCart


    companion object {
        @Volatile
        private var instance: DataBaseRoom? = null

        private val lock = Any()

        operator fun invoke(context: Context) = instance
            ?: synchronized(lock) {
                instance
                    ?: makeDatabase(
                        context
                    ).also {
                        instance = it
                    }
            }

        private fun makeDatabase(context: Context) = Room.databaseBuilder(
            context.applicationContext,DataBaseRoom::class.java,"name"
        ).build()
    }

}```
this is my Dao : 
```//address table dao

        @Query("SELECT * FROM addresstable")
        fun getalladress () : LiveData<Addresstb>


        @Insert(onConflict = OnConflictStrategy.REPLACE)
        suspend fun insertaddress (model : Addresstb)


        @Query("DELETE FROM addresstable")
       suspend fun deleteaddress ()

这是我的viewmodel:


    fun getalladdress() = db.GetDao().getalladress()

    suspend fun deleteaddress() = db.GetDao().deleteaddress()

    suspend fun insertaddress(model : Addresstb) = db.GetDao().insertaddress(model)

这是我获取新插入内容的片段:



    fun getaddress() = repository.getalladdress()


    fun deleteaddres() = Coroutinescope(dispatchers.Default).launch {


        repository.deleteaddress()

    }


    fun insertaddress(model : Addresstb) = Coroutinescope(dispatchers.Default).launch {


        repository.insertaddress(model)

这是我将数据插入数据库的地方:

class ChosseAddress : Fragment() {


    lateinit var viewmodelRoom: viewmodelRoom

    override fun onCreateView(
        inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?
    ): View? {


        val vl = inflater.inflate(R.layout.choose_address_layout,container,false)


        val database = DataBaseRoom(requireContext())
        val repository = RepositoryCart(database)
        val factoryRoom = FactoryRoom(repository)


        viewmodelRoom =
            viewmodelProvider(viewmodelStoreOwner { viewmodelStore() },factoryRoom).get(
                viewmodelRoom::class.java
            )
        viewmodelRoom.getaddress().observe(viewLifecycleOwner,Observer {


            try {

                vl.txt_address.text = it.address


            } catch (ex: Exception) {
                null
            }

        })



        val animsec: Animation =
            AnimationUtils.loadAnimation(vl.context,R.anim.anim_for_btn_zoom_out)

        vl.button_back_choose_address.setonClickListener {

            it.startAnimation(animsec)


            childFragmentManager.beginTransaction()
                .replace(R.id.choose_address_container,HamburgerFragment())
                .commit()

        }

        vl.edit_address.setonClickListener {


            val mycustomview =
                LayoutInflater.from(context).inflate(R.layout.alertfialog_costume,null)
            val dialogtext = LayoutInflater.from(context).inflate(R.layout.edit_alert_txt,null)

            val mBuilder = AlertDialog.Builder(context)
                .setView(mycustomview)
                .setCustomTitle(dialogtext)
            val show = mBuilder.show()

            mycustomview.edit_manually.setonClickListener {

                show.dismiss()
                childFragmentManager.beginTransaction()
                    .replace(R.id.choose_address_container,ManuallyAddressFragment())
                    .commit()


            }


        }



        return vl


    }


}```

我尝试过,所以事情也使用了更新方法,但是数据库只是返回了第一个参数,我想要新的插入值...

解决方法

对于初学者来说,如果您要获取所有地址,则应如下所示:

    @Query("SELECT * FROM addresstable")
    fun getalladress () : LiveData<List<AddressTb>>

要选择一个地址,请使用类似以下内容:

@Query("SELECT * FROM addresstable WHERE id= :id")
fun findAddressById(id: Long) : AddressTb
,

要使用相同的ID来更新值,就像在代码中一样,我看到您尝试插入新对象 AddressTb(null,edittext.text.toString()),您正在传递 null 值作为 id 的值,将要更新的AddressTb对象的ID传递给getalladdress。