How display data in a Text View using Room Library Android?

Viewed 496

I'm new in Android. I'm developing an application that display 10 words and their meaning one by one. My question is how do i display data one by one from Model View which contain LiveData<List< >> variable to Text View . The process should by like this: retrieving data from database to Repository to View Model and finally display it in UI Text View. Any suggestion except using Recycle View?enter image description here.

@Entity(tableName = "word_table")
data class Word(
        @ColumnInfo(name = "English")
        val English: String,
        @ColumnInfo(name = "Italian")
        val Italian: String
)
{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    var id: Int = 0


    fun Word(id: Int) {
        this.id = id
    }
@Dao
interface WordDao {

   
    @Query("SELECT * FROM word_table ")
    fun getWords(): Flow<List<Word>>
class WordRepository(private val wordDao: WordDao) {
  
    val allWords: Flow<List<Word>> = wordDao.getWords()
  
    }


class WordViewModel(private val repository: WordRepository) : ViewModel() {
   
    val allWords: LiveData<List<Word>> = repository.allWords.asLiveData()
  
    }
}
2 Answers

You can combine the allWords Flow with a Flow that keeps track of which element of the list is shown, and uses them to produce a flow of individual words. Then create a separate public function for incrementing the word index.

class WordViewModel(private val repository: WordRepository) : ViewModel() {

    private val wordIndex = MutableStateFlow(0)
    val word: LiveData<Word> = repository.allWords.combine(wordIndex) { list, index -> 
        list[index % list.size] // % operator allows wrap-around
    }.asLiveData()

    fun incrementWord() {
        wordIndex.value += 1
    }
  
}

Then in your Fragment/Activity, observe the LiveData and use the value to set the text of your TextViews. And make the Next button call the incrementWord() function of the ViewModel.

If you want to also add and remove words while this ViewModel is alive, this could get a little trickier because adding or removing a word will change what word is currently shown and possibly skip one in the rotation.

In UI Activity write:

val txt1=findViewById<TextView>(R.id.textView1)
val txt2=findViewById<TextView>(R.id.textView2)

val wordViewModel: LiveData<List<Word>> = wordViewModel.allWords

wordViewModel.allWords.observe(this) { words ->
           
              txt1.text=words[1].word
              txt2.text=words[2].word
   
        }
Related