How to read DataBaseRoom and display a textView

I am practicing with dataBaseRoom, for them I have created a button, which allow me to read database , i want to put the name of a user and when pressing the button (read data base) reflects me, his name, last name and age in the texview,the problem is that I do not know how to display the data in a textView.

Activity where I want to carry out the actions

enter image description here


@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true)@ColumnInfo(name = "id") val id: Int,
    val firstName: String,
    val lastName: String,
    val age: Int


interface UserDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun addUser(user: User)
    @Query("SELECT * FROM user_table ORDER BY id ASC")
    fun readAllData(): LiveData<List<User>>


@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
    companion object {
        private var INSTANCE: UserDatabase? = null

        fun getDatabase(context: Context): UserDatabase{
            val tempInstance = INSTANCE
            if(tempInstance != null){
                return tempInstance
                val instance = Room.databaseBuilder(
                INSTANCE = instance
                return instance


class UserRepository(private val userDao: UserDao) {
    val readAllData: LiveData<List<User>> = userDao.readAllData()
    suspend fun addUser(user: User){


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

    private val readAllData: LiveData<List<User>>
    private val repository: UserRepository

    init {
        val userDao = UserDatabase.getDatabase(application).userDao()
        repository = UserRepository(userDao)
        readAllData = repository.readAllData

    fun addUser(user: User){
        viewModelScope.launch(Dispatchers.IO) {


I want to add my texview in this class

class ListFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
       val view =  inflater.inflate(R.layout.fragment_list, container, false)

        return view


Read more here:

Content Attribution

This content was originally published by Jorge Leonardo at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: