使用Room,ViewModel和LiveData更改数据后重新加载RecyclerView

时间:2017-09-01 12:16:11

标签: android mvvm viewmodel android-room android-livedata

我正在努力,但没有成功,几天来解决问题。每当特定模型的记录在数据库(DB Room)中发生变化时,我想更新我的recyclerView。我使用ViewModel来处理模型数据,记录列表存储在LiveData中。

数据库

@Database(entities = arrayOf(Additive::class), version = ElementDatabase.DB_VERSION, exportSchema = false)
    abstract class ElementDatabase() : RoomDatabase() {

        companion object {
            const val DB_NAME : String = "element_db"
            const val DB_VERSION : Int = 1

            fun get(appContext : Context) : ElementDatabase {
                return Room.databaseBuilder(appContext, ElementDatabase::class.java, DB_NAME).build()
            }
        }

        abstract fun additivesModels() : AdditiveDao

    }

模型

@Entity
class Additive {

    @PrimaryKey @ColumnInfo(name = "id")
    var number : String = ""
    var dangerousness : Int = 0
    var description : String = ""
    var names : String = ""
    var notes : String = ""
    var risks : String = ""
    var advice : String = ""
}

@Dao
interface AdditiveDao {

    @Query("SELECT * FROM Additive")
    fun getAllAdditives() : LiveData<List<Additive>>

    @Query("SELECT * FROM Additive WHERE id = :arg0")
    fun getAdditiveById(id : String) : Additive

    @Query("DELETE FROM Additive")
    fun deleteAll()

    @Insert(onConflict = REPLACE)
    fun insert(additive: Additive)

    @Update
    fun update(additive: Additive)

    @Delete
    fun delete(additive: Additive)
}

视图模型

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

    private var elementDatabase : ElementDatabase
    private val additivesModels : LiveData<List<Additive>>

    init {
        this.elementDatabase = ElementDatabase.get(appContext = getApplication())
        this.additivesModels = this.elementDatabase.additivesModels().getAllAdditives()
    }

    fun getAdditivesList() : LiveData<List<Additive>> {
        return this.additivesModels
    }

    fun deleteItem(additive : Additive) {
        DeleteAsyncTask(this.elementDatabase).execute(additive)
    }

    private class DeleteAsyncTask internal constructor(private val db: ElementDatabase) : AsyncTask<Additive, Void, Void>() {

        override fun doInBackground(vararg params: Additive): Void? {
            db.additivesModels().delete(params[0])
            return null
        }

    }
}

片段

class AdditivesFragment : LifecycleFragment() {

    private var viewModel : AdditiveViewModel? = null
    private var adapter : AdditivesAdapter? = null

    companion object {
        fun newInstance() : AdditivesFragment {
            val f = AdditivesFragment()
            val args = Bundle()

            f.arguments = args
            return f
        }
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater?.inflate(R.layout.fragment_additives, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        this.adapter = AdditivesAdapter(ArrayList<Additive>())
        this.additives_list.layoutManager = GridLayoutManager(this.context, 2, GridLayoutManager.VERTICAL, false)
        this.additives_list.adapter = this.adapter

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

        this.viewModel?.getAdditivesList()?.observe(this, Observer<List<Additive>> { additivesList ->
            if(additivesList != null) {
                this.adapter?.addItems(additivesList)
            }
        })
        super.onActivityCreated(savedInstanceState)
    }
}

现在,我的问题是为什么观察者只调用一次(在片段的开头)然后再没有被回调?如何让观察者不断监听数据库中的更改(插入,更新,删除),以便我的recyclerView可以立即更新?非常感谢任何建议。

1 个答案:

答案 0 :(得分:2)

这是您犯错的地方:

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

您在this内时正在传递fragment,这对于某些人来说是非常令人不安的,因为这不是语法错误,而是合乎逻辑的。您必须通过activity!!,就像这样:

this.viewModel = ViewModelProviders.of(activity!!).get(AdditiveViewModel::class.java)