房间数据未显示在 RecyclerList 中 [英] Room Data doesn't show in the RecyclerList

查看:24
本文介绍了房间数据未显示在 RecyclerList 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是第一次使用 Room Data,同时也使用 MVVM 模式.目的是我希望我的数据出现在 RecyclerList 上,但它不会关闭,也不会向我显示任何错误,它只是显示为空.

It's first time using Room Data while also using MVVM pattern. The aim is that I want my data to appeard on the RecyclerList but it's doesn't shut down nor shows me any error it's just appears empty.

这是我的数据库类:

@Database(entities = [Plant::class, Plant_Category::class], version = 1)
abstract class PlantDatabase:RoomDatabase() {
    abstract fun plantDao(): PlantOperations
    abstract fun plantCategoryDao(): PlantCategoryOperations

    companion object {
        private var INSTANCE: PlantDatabase? = null
             
        fun getDatabase(context: Context): PlantDatabase {
            if (INSTANCE == null) {

                INSTANCE = Room.databaseBuilder(
                    context.applicationContext,
                    PlantDatabase::class.java, DB_NAME // contains directory of sqlite database
                ) 
                    .fallbackToDestructiveMigration()
                    .build()
            }

            return INSTANCE!!
        }
    }
}

我的道类:

@Dao
interface PlantOperations {
    @Query("SELECT * FROM Plant")
    fun getAll(): Flow<List<Plant>>

    @Insert
    fun insertPlant( plant: Plant)

    @Delete
    fun delete(plant:Plant)

    @Update
    fun updatePlant(plant:Plant)}

这是我的存储库类:

class PlantRepository(application:Application){
    private var allPlants = MutableLiveData<List<Plant>>()

    private val plantDAO = PlantDatabase.getDatabase(application).plantDao()

    init {
        CoroutineScope(Dispatchers.IO).launch {
            val plantData = plantDAO.getAll()
            plantData.collect{
                allPlants.postValue(it)
            }
        }
    }
    fun getAllPlants(): MutableLiveData<List<Plant>> {
        return allPlants
    }
    

}

我的视图模型类:

class PlantViewModel(
            application: Application
    ): AndroidViewModel(application) {

        private var repository = PlantRepository(application)

        private var _allPlants = repository.getAllPlants()

        val allPlants: MutableLiveData<List<Plant>>
            get() = _allPlants
    }

我的片段回收器:

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

        lateinit var  photoAdapter: Photo_Adapter
        lateinit var plantViewModel: PlantViewModel

       
        val view: View = inflater.inflate(R.layout.fragment_edit__form, container, false)
        val fab = view.findViewById(R.id.floatingActionButton) as FloatingActionButton
        val recyclerView = view.findViewById(R.id.recyclerView) as RecyclerView
          
      

        recyclerView.layoutManager = GridLayoutManager(context, 2)
        photoAdapter = Photo_Adapter(context)
        recyclerView.adapter = photoAdapter

         plantViewModel = ViewModelProvider(this).get(PlantViewModel::class.java)
        plantViewModel.allPlants.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            photoAdapter.setDataList(it)
        })

       // photoAdapter.setDataList(dataList)
        //Floating button that opens the Form in order to add plant
        fab?.setOnClickListener {

            val intent = Intent(view.context, Edit_Form::class.java)
           startActivity(intent);
        }
        return view
    }


这是我的适配器类:

class Photo_Adapter(var context: Context?) : RecyclerView.Adapter<Photo_Adapter.ViewHolder>() {

        var dataList = emptyList<Plant>()

        internal fun setDataList(dataList: List<Plant>) {
            this.dataList = dataList
            notifyDataSetChanged()
        }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // Get the data model based on position
        var data = dataList[position]


        holder.title.text = data.name
        holder.desc.text = data.type.toString()


        holder.image.setImageResource(data.image)
        holder.relativeLayout.setOnClickListener { view -> //Toast.makeText(view.getContext(),"click on item: "+model.getTitle(),Toast.LENGTH_LONG).show();
            val intent = Intent(view.context, PlantDetails::class.java)
            intent.putExtra("plant_name", data.name)
            intent.putExtra("plant_image",data.image)
            intent.putExtra("plant_type", data.type.type)
            intent.putExtra("plant_water", data.type.water_time)
            intent.putExtra("plant_details", data.type.details)
            view.context.startActivity(intent)
    }

}
        // Provide a direct reference to each of the views with data items

        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var image: ImageView
            var title: TextView
            var desc: TextView
            var relativeLayout: CardView

            init {
                image = itemView.findViewById(R.id.image)
                title = itemView.findViewById(R.id.title)
                desc = itemView.findViewById(R.id.desc)
                relativeLayout = itemView.findViewById<View>(R.id.relativeLayout) as CardView
            }

        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Photo_Adapter.ViewHolder {

            // Inflate the custom layout
            var view = LayoutInflater.from(parent.context).inflate(R.layout.photo_layout, parent, false)
            return ViewHolder(view)
        }


        //  total count of items in the list
        override fun getItemCount() = dataList.size

}

也许我忘了添加什么?无论如何,我将感谢您的帮助.

Perhaps I forgot to add something? In Anyway I will be grateful for your help.

推荐答案

您不应该观察存储库中的数据,您的活动/视图应该观察这些数据.看看这个:

You should not observe data on your repository, your activity/view should observe this data. Take a look at this:

首先,将此依赖项添加到您的 gradle:

First, add this dependency to your gradle:

implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"

然后在您的存储库中

class PlantRepository(application:Application){
     private val plantDAO = PlantDatabase.getDatabase(application).plantDao()
     fun getAllPlants(): Flow<List<Plant>> = plantDAO.getAll()
}

在您的视图模型中:

class PlantViewModel(
        application: Application
): AndroidViewModel(application) {
    private var repository = PlantRepository(application)
    val allPlants = repository.getAllPlants()
                   .flowOn(Dispatchers.IO)
                   .asLiveData()
}

并且您的活动很好,但请检查您的适配器,确保您正在通知您的适配器您的列表已更改.您也可以在您的视图中处理(收集)流,但这取决于您

And your activity is fine, but check your adapter, make sure that you're notifing your adapter that your list has changed. You can also work (collect) flows on your view, but this depends on you

这篇关于房间数据未显示在 RecyclerList 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆