gpt4 book ai didi

android - 如何通过VIEWMODEL从数据库(MODEL)中的Activity(VIEW)获取添加的对象的ID。 Android,MVVM

转载 作者:行者123 更新时间:2023-12-03 10:41:17 40 4
gpt4 key购买 nike

  • 我有一个基于 MVVM体系结构Android 构建的ShoppingList应用程序。
  • 我没有做到,但我遵循了有关YouTube的教程。
  • 这是显示购物 list 的app(1/2)的图像。右下角是用于添加列表的新元素的按钮。

  • enter image description here
  • 这是第二个 View (2/2),其中出现对话框以输入元素的名称和数量。在这里,我们有取消按钮和添加按钮

  • enter image description here
    问题是,当我单击对话框上的 ADD按钮时,我不知道如何在VIEW的“回收者” View 中获取此添加项的ID,并使其通过我的主Activity上的TOAST命令显示。
    问题是- ,当我单击“添加”按钮时,如何获取新添加的元素的ID到我的购物 list 中并将其显示在MainActivity(ShoppingActivity)VIEW中?
    如果您需要其他信息,请立即联系我!我会为您提供所需的任何东西。
    此处提供代码:
    ShoppingActivity(查看)
    class ShoppingActivity : AppCompatActivity(), KodeinAware {
    override val kodein by kodein()
    private val factory: ShoppingViewModelFactory by instance()

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_shopping)

    // View Model is being created out of other classes to set changes to View

    val viewModel = ViewModelProviders.of(this, factory).get(ShoppingViewModel::class.java)

    // Adapters and Recycler View

    val adapter = ShoppingItemAdapter(listOf(), viewModel)
    rvShoppingItems.layoutManager = LinearLayoutManager(this)
    rvShoppingItems.adapter = adapter


    // ViewModel makes changes to the Activity

    viewModel.getAllShoppingItems().observe(this, Observer {
    adapter.items = it
    adapter.notifyDataSetChanged()
    })

    fab.setOnClickListener {
    AddShoppingItemDialog(this ,
    object: AddDialogListener{
    override fun onAddButtonClicked(item: ShoppingItem) {
    viewModel.upsert(item)
    showToast(viewModel.getID(item).toString().toInt())

    }
    }).show()
    }

    }

    fun showToast(id: Int) {
    Toast.makeText(this@ShoppingActivity, "ID записи: $id", Toast.LENGTH_LONG).show()
    }}
    ShoppingViewModel(ViewModel)
    class ShoppingViewModel(private val repository: ShoppingRepository): ViewModel() {

    fun upsert(item: ShoppingItem) = CoroutineScope(Dispatchers.IO).launch {
    repository.upsert(item)
    }

    fun delete(item: ShoppingItem) = CoroutineScope(Dispatchers.IO).launch {
    repository.delete( item)
    }

    fun getID(item: ShoppingItem) = repository.getID(item)


    fun getAllShoppingItems() = repository.getAllShoppingItems()

    }
    AddShoppingItemDialog(显示对话框信息的逻辑)
    class AddShoppingItemDialog(context: Context, var addDialogListener: AddDialogListener): AppCompatDialog(context)  {

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.dialog_add_shopping_item)

    tvAdd.setOnClickListener {
    val name = etName.text.toString()
    val amount = etAmount.text.toString()

    if(name.isEmpty()) {
    Toast.makeText(context, "Please enter the name", Toast.LENGTH_LONG).show()

    return@setOnClickListener
    }

    if(amount.isEmpty()) {

    Toast.makeText(context, "Please enter the amount", Toast.LENGTH_LONG).show()

    return@setOnClickListener
    }

    val item = ShoppingItem(name, amount.toInt())

    // We need to

    addDialogListener.onAddButtonClicked(item)
    dismiss()
    }

    tvCancel.setOnClickListener {
    cancel()
    }
    }}
    存储库
    class ShoppingRepository(private val db: ShoppingDatabase) {

    suspend fun upsert(item: ShoppingItem) = db.getShoppingDao().upsert(item)
    suspend fun delete(item: ShoppingItem) = db.getShoppingDao().delete(item)
    fun getID(item: ShoppingItem) = db.getShoppingDao().getID(item)

    fun getAllShoppingItems() = db.getShoppingDao().getAllShoppingItems()}
    购物DAO
    @Dao
    interface ShoppingDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(item: ShoppingItem) : Long

    @Delete
    suspend fun delete(item: ShoppingItem)

    @Query("SELECT * FROM shopping_items WHERE id = $CURRENT_POSITION")
    fun getID(item: ShoppingItem): LiveData<Int>

    @Query("SELECT * FROM shopping_items")
    fun getAllShoppingItems(): LiveData<List<ShoppingItem>>
    }
    购物商品
    const val CURRENT_POSITION = 0

    @Entity(tableName = "shopping_items")

    data class ShoppingItem(


    @ColumnInfo(name = "item_name")
    var name: String,
    @ColumnInfo(name = "item_amount")
    var amount: Int
    ) {

    @PrimaryKey(autoGenerate = true)
    var id: Int? = CURRENT_POSITION


    }
    AddDialogListener
    interface AddDialogListener {

    fun onAddButtonClicked(item: ShoppingItem)
    }
    已添加项目的App View
    enter image description here

    最佳答案

    由于对数据库的插入/向上插入操作是挂起函数,因此请在 View 模型中观察返回的id
    ShoppingViewModel

    private var _itemId : Long = MutableLiveData<Long>()
    val itemId : LiveData<Long>
    get() = _itemId

    fun upsert(item: ShoppingItem) = CoroutineScope(Dispatchers.IO).launch {
    val id = repository.upsert(item)
    _itemId.postValue(id)
    }
    ShoppingActivity中,
    viewModel.itemId.observe(this, Observer {id ->
    showToast(id)

    })
    如果您需要了解更多详细信息,请告诉我。

    关于android - 如何通过VIEWMODEL从数据库(MODEL)中的Activity(VIEW)获取添加的对象的ID。 Android,MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66203578/

    40 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com