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

迪亚斯·马希科夫(Dias Mashikov)
  • 我有一个基于MVVM体系结构Android的ShoppingList App
  • 我没有做到,但是我遵循了有关YouTube的教程。
  • 这是显示购物清单的app(1/2)的图像。右下角是用于添加列表的新元素的按钮。

在此处输入图片说明

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

在此处输入图片说明

The problem is when I click the ADD button on the Dialog Box I do not know how to get an ID of this added item to the recycler view on my VIEW and to make it appear via the TOAST command on my main Activity.

The question is - How to get an ID of a new added element to my shopping list and show it on my MainActivity(ShoppingActivity) VIEW when I click the ADD button?

If you need additional information ask me out immediately! I will provide you anything you need.

Code is provided here:

ShoppingActivity(View)

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(the logic of showing Dialog info)

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()
    }
}}

Repository

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()}

ShoppingDAO

@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>>
}

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 with added items

在此处输入图片说明

Varsha Kulkarni

由于对数据库的插入/向上插入操作是挂起函数,因此请在视图模型中观察返回的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)

})

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何通过ID获取数据库中的项目?

如何在Django数据库中获取对象的ID

Django 数据库查询:如何通过 id 获取多个对象?

从数据库中获取对象的父ID(由MVC通过虚拟ICollection创建)

如何通过 url 中的特定 id 从 MySQL 数据库中获取数据

如何通过View Model,Repository和DAO从Room数据库中读取值?

如何通过使用Codeigniter中的ID数组从数据库获取数据?

如何通过 id 从数据库获取特定值

如何通过ID从数据库获取内容标题

如何从数据库获取与ID对象相关的信息

在角度2中添加功能,如何获取联系人数据库的新ID?

通过改造从数据库中获取xAxis mpchart android

如何通过查询获取MySQL中的数据库结构

如何选择数据库中添加从数据库中获取的选项到最后

如何在Fixtures Symfony中从数据库获取对象

如何从listView(数据库)获取_id [android]

Android-在数据库onItemClick中获取_id

无法从Android中的数据库获取正确的ID

如何在 Kotlin 的 android 房间数据库中获取插入行的 id?

Android如何从onListItemClick中获取ListView ID并使用它?ListView,通知,SQLite数据库

我如何从数据库 firebase 中获取推送 ID

如何获取数据库中特定ID的记录数量?

如何根据id从数据库中获取值

如何使用View中的下拉列表将数据从ViewModel插入数据库

如何从筛选器中的数据库中获取用户并在jwt响应中添加ID?

添加从数据库中获取的数字

从数据库中获取状态对象

如何通过MVVM模式中的小部件与数据库进行交互

如何获取Android中Room数据库的行数?