Reload RecyclerView after data change with Room, ViewModel and LiveData

7k views Asked by At

I am trying, without success, to solve a problem for days. I would like to update my recyclerView whenever the records of a particular model change in the Database (DB Room). I use ViewModel to handle the model data and the list of records are stored in LiveData.

Database

@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

    }

Model

@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

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

ViewModel

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
        }

    }
}

Fragment

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

Now, my question is why is the observer called only once (at the start of the fragment) and then is not called back again? How can I keep the observer constantly listening to the changes in the DB (insert, update, delete) so that my recyclerView instantly can be updated? Thanks a lot for any suggestion.

1

There are 1 answers

0
USMAN osman On

This is where you made a mistake:

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

you are passing this while you are inside the fragment which is pretty disturbing for some people cause it is not a syntax error but logical. You have to pass activity!! instead, it will be like this:

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

UPDATE:
Pass viewLifecycleOwner while being inside fragment while observing the Data

mainViewModel.data(viewLifecycleOwner, Observer{})

If you're using fragmentKtx, you can init viewModel this way:

private val viewModel by viewModels<MainViewModel>()

If You've viewModelFactory:

private val viewModel by viewModels<MainViewModel>{
   viewModelFactory
}

with this approach you don't need to call:

// you can omit this statement completely
viewModel = ViewModelProviders.of(this).get(AdditiveViewModel::class.java)

You can simply just start observing the data..