Priyanka Kadam
Priyanka Kadam

Reputation: 145

Set data from Viewmodel to activity android kotlin

I am new to the MVVM architecture. I get data from db in my viewmodel and now I want to set that data to EditTexts in activity

    class EmployeeViewModel : BaseViewModel<EmployeeNavigator>() {

    var userList = ArrayList<EmployeeResponse>()
    var mName = MutableLiveData<EmployeeResponse>()


    fun fetchUsersAndSaveInDB(toString: String) {
        dialogMessage.value = "Fetching Data..."
        dialogVisibility.value = true
        mDisposable.add(DataProvider.fetchUsersAndSave(Consumer {
            getUsersFromDB()
        }, Consumer {
            checkError(it)
        }, toString))
    }

    private fun getUsersFromDB() {
        mDisposable.add(DataProvider.getUsersFromDb(Consumer {
            dialogVisibility.value = false
            userList = it as ArrayList<EmployeeResponse>
            mName.value = userList[0]
        }, Consumer { checkError(it) }))
    }

}

I got data in mName object now I want to set this data to edittexts in my activity. How can I achieve this ?

Upvotes: 2

Views: 9086

Answers (3)

haresh
haresh

Reputation: 1420

In Activity Do below three steps :

1.Declare your ViewModel in activity.

private lateinit var viewModel: EmployeeViewModel
  1. Initialize your viewmodel :

     viewModel = ViewModelProviders.of(this).get(PostViewModel::class.java)
    
  2. Observer your data from ViewModel :

     viewModel.getWhateverData()
             .observe(this,
                 Observer<List<"Your class">> { userPost ->
                     adapter?.setPosts(userPost)
                     recycler_view.adapter = adapter
                 })
    

Also in your viewmodel method you have not mentioned what exactly you want to observe.

Demo Of viewmodel

class PostViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: PostRepository = PostRepository()
    private var userId: Int = -1
    lateinit var userPost: LiveData<List<Post>>

    fun getUserPost(id: Int): LiveData<List<Post>> {
        this.userId = id
        userPost = repository.getUserPost(id)
        return userPost
}
}

Let me know if still any help required also so can look into below demo if needed.

Upvotes: 2

Dmitrii Leonov
Dmitrii Leonov

Reputation: 1389

Here is more Kotlin way to do it.

Add this dependency to make observe function look shorter

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-rc03'

If you have only one functional parameter you don't need to pass it inside the curly brackets. So in Activity you can do next:

mViewModel.mName.observe(this) {
    it?.let { tv_emp_name.setText(it.empName) }
}

Also following Kotlin style guidelines it's better to use camelCase naming (Hungarian notation is allowed in this case) for layout IDs if you are using kotlinx.android.synthetic. You might also remove m prefix for variables.

Following all these your code would look like:

viewModel.name.observe(this) {
    it?.let { tvEmpName.setText(it.empName) }
}

Upvotes: 4

Priyanka Kadam
Priyanka Kadam

Reputation: 145

  mViewModel.mName.observe(this, Observer {
      if (it != null) {
          tv_emp_name.setText(it.empName)
      }
  })

Written this code in Activity and able to set data to EditText

Upvotes: 2

Related Questions