如何从房间数据库中删除recyclerrview项目

时间:2020-04-26 05:12:33

标签: java android android-studio kotlin

我有一个正在开发的程序。我需要这样做,以便在输入食物名称后单击“删除”按钮时,它会从列表和数据库中删除回收者视图项。这是我的意思的屏幕截图:

Image of app

我已经复制并粘贴了一些我需要修改的主要结构。我只是不知道我到底需要做什么。这些部分已被注释掉。

这是MainActivity.kt中的代码:

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private var adapter: FoodListAdapter? = null
    private lateinit var viewModel: MainViewModel

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

        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

        adapter = FoodListAdapter(R.layout.food_row)
        food_recycler.layoutManager = LinearLayoutManager(this)
        food_recycler.adapter = adapter

        buttonAdd.setOnClickListener { viewModel.insertFood(Food(editFoodName.text.toString())) }

      //  buttonDelete.setOnClickListener { viewModel.insertFood(Food(editFoodName.text.toString())) }


        viewModel.allFoods?.observe(this, Observer { foods ->
            foods?.let  {
                adapter?.setFoodList(it)
            }
        })
    }
}

FoodDao.kt中的代码:

import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query

@Dao
interface FoodDao {
    @Insert
    fun insertFood(product: Food)

    @Query("SELECT * FROM foods")
    fun getAllFoods(): LiveData<List<Food>>

    @Query ("SELECT * FROM foods WHERE foodName = :name")
    fun findFood(name: String) : List<Food>
}

MainViewModel.kt中的代码:

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel

class MainViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: FoodRepository =
        FoodRepository(application)

    var allFoods:  LiveData<List<Food>>?

    init {
        allFoods = repository.allFoods
    }

    fun insertFood(food: Food) {
        repository.insertFood(food)
    }

//    fun deleteFood(food: Food) {
//        repository.deleteFood(food)
//    }


}

FoodRepository.kt中的代码:

import android.app.Application
import android.os.AsyncTask
import androidx.lifecycle.LiveData

class FoodRepository(application: Application) {
    val allFoods: LiveData<List<Food>>?

    private var foodDao: FoodDao?

    init {
        val db: FoodDatabase? =
            FoodDatabase.getDatabase(application)
        foodDao = db?.foodDao()
        allFoods = foodDao?.getAllFoods()
    }

    fun insertFood(newfood: Food) {
        val task = InsertAsyncTask(foodDao)
        task.execute(newfood)
    }

    private class InsertAsyncTask constructor(private val asyncTaskDao: FoodDao?) :
        AsyncTask<Food, Void, Void>() {

        override fun doInBackground(vararg params: Food): Void? {
            asyncTaskDao?.insertFood(params[0])
            return null
        }
    }

//    fun deleteFood(newfood: Food) {
//        val task = DeleteAsyncTask(foodDao)
//        task.execute(newfood)
//    }
//
//    private class DeleteAsyncTask constructor(private val asyncTaskDao: FoodDao?) :
//        AsyncTask<Food, Void, Void>() {
//
//        override fun doInBackground(vararg params: Food): Void? {
//            asyncTaskDao?.insertFood(params[0])
//            return null
//        }
//    }
}

2 个答案:

答案 0 :(得分:1)

这里的事情是,您需要使用新数据更新回收者视图:

recyclerView?.notifyDataSetChanged() 

答案 1 :(得分:1)

首先,设置删除方法设置。

@Delete
    fun deleteFood(product: Food);

您的视图模型方法正确,存储库方法正确。您在活动中调用方法。

 buttonDelete.setOnClickListener { viewModel.deleteFood(Food(editFoodName.text.toString())) }

调用所有食物时,您需要使用新数据更新回收者视图。

viewModel.allFoods?.observe(this, Observer { foods ->
            foods?.let  {          
                adapter?.setFoodList(it)
              recyclerView?.notifyDataSetChanged() 


            }
        })