How to read DataBaseRoom and display a textView

陌路散爱 提交于 2021-01-29 06:49:21

问题


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

//Entity

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

//Dao

 @Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun addUser(user: User)

    @Query("SELECT * FROM user_table ORDER BY id ASC")
    fun readAllData(): LiveData<User>
    
}

//DataBase

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

        fun getDatabase(context: Context): UserDatabase{
            val tempInstance = INSTANCE
            if(tempInstance != null){
                return tempInstance
            }
            synchronized(this){
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "user_database"
                ).build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

//Repository

 class UserRepository(private val userDao: UserDao) {
    
    val readAllData: LiveData<User> = userDao.readAllData()

    suspend fun addUser(user: User){
        userDao.addUser(user)
    }

}

//ViewModel

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

    val readAllData: LiveData<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) {
            repository.addUser(user)
        }
    }

}

I want to add my texview in this class

  mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
        mUserViewModel.readAllData.observe(viewLifecycleOwner, Observer {

            textView1.text = it.firstName
            textView2.text = it.lastName
            textView3.text = it.age.toString()


        })

回答1:


In your fragment add an observer to the LiveData and set the TextView value within the observer.

See the documentation here.


To get the data of the latest added user in the fields, you can use this (check whether .size or .length is correct for you):

    mUserViewModel.readAllData.observe(viewLifecycleOwner, Observer { users ->
        if (users != null) {
            for (user in users) { // I'm not sure about kotlin syntax 
                if (user.firstName == enteredFirstName &&
                             user.lastName == enteredLastname) {   
                    textViewFirstName.text = user.firstName
                    textViewLastName.text = user.lastName
                    textViewAge.text = user.age.toString()


来源:https://stackoverflow.com/questions/64850505/how-to-read-databaseroom-and-display-a-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!