简体   繁体   中英

How to update a text view from a Room database using LiveData?

I'm trying to create a simple counter app that uses Databinding, Room database, and live data. Currently when the user presses the plus button, it updates a local live data value which then updates the database number. When I try to attach the value from the database dbCount, I get an databinding error. How can I get the live data from the database to the text view?

Note: I'm new to android development so I'm still learning the concepts. Project Repository

fragment_number.xml

<TextView
            android:id="@+id/dbView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{sleepTrackerViewModel.dbCount}"
            app:layout_constraintBottom_toTopOf="@+id/display"
            app:layout_constraintEnd_toEndOf="@+id/display"
            app:layout_constraintStart_toStartOf="@+id/display" />

DatabaseDAO

   //Selects first entry
    @Query("SELECT number from daily_sleep_quality_table WHERE nightId = 1")
    fun getFirst(): LiveData<Int>

NumberViewModel

    private val dbCount = database.getFirst()

//Holds the count
    private val _count = MutableLiveData<Int>()
    val count: LiveData<Int>
        get() = _count


       fun plus(){
        uiScope.launch{
            //adds to current count
            _count.value = (_count.value)?.plus(1)

            //Gets entry with ID 1 and updates number
            withContext(Dispatchers.IO) {
                val currentNum = database.get(1) ?: return@withContext

                currentNum.number = _count.value!!

                database.update(currentNum )
            }


            number.value = getTonightFromDatabase()
        }
    }

in your view just call the NumberViewModel count like this

private lateinit var viewModel: NumberViewModel

if you using fragment put the function on onActivityCreated if you using activity put it onCreate

viewModel = ViewModelProviders.of(this).get(NumberViewModel::class.java)
viewmodel.count.observe(this,Observe{count->
     dbView.text = count
})

It's very easy if you apply the KOIN for binding ViewModel and your DB here the reference about KOIN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM