1

I am trying to implement MVVM arcitecture in Kotlin using data binding. the code just shows blank screen as an output. Can anybody help me to figureout why there is no call to the server while executing this program.

I tried this and links similar to this to solve the issue.

My Code is as follows:

MainActivity

class MainActivity : AppCompatActivity() {

private var cvViewModel: CvViewModel? = null
private var model: Model?= null
private var liveData: LiveData<Model>? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding : ActivityMainBinding= DataBindingUtil.setContentView(this, R.layout.activity_main)
   // setContentView(R.layout.activity_main)
    cvViewModel= ViewModelProviders.of(this).get(CvViewModel::class.java)
    liveData= cvViewModel.getNewsRepository()
}

}

class CvRepository {

private val apiCall: ApiCall=
    RetrofitClient.cteateService(ApiCall::class.java)


fun getCvDetails(): MutableLiveData<Model> {
    val cvData = MutableLiveData<Model>()
    apiCall.getCvData().enqueue(object : Callback<Model> {
        override fun onResponse(call: Call<Model>,
                                response: Response<Model>
        ) {
            if (response.isSuccessful) {
                Log.e("abc", ""+response.body().toString())
                cvData.value = response.body()
            }
        }

        override fun onFailure(call: Call<Model>, t: Throwable) {
            cvData.value = null
        }
    })
    return cvData
}

companion object {

    private var cvRepository: CvRepository ? = null

    val instance: CvRepository
        get() {
            if (cvRepository == null) {
                cvRepository = CvRepository()
            }
            return this.cvRepository as CvRepository
        }
}

}

class CvViewModel: ViewModel(){

private var mutableLiveData: MutableLiveData<Model>? = null
private var cvRepository: CvRepository? = null

fun init() {
    if (mutableLiveData != null) {
        return
    }
    cvRepository = CvRepository.instance
    mutableLiveData = cvRepository!!.getCvDetails()
}

fun getNewsRepository(): LiveData<Model>? {
    return mutableLiveData
}

}

Preet Kaur
  • 73
  • 1
  • 1
  • 3

1 Answers1

1

Your getCvDetails() inside CvRepository return empty list as enqueue is asynchronous. That's why data not populated in your view.

Try directly passing the repository LiveData to Activity from ViewModel

fun getNewsRepository(): LiveData<Model>? {
    return CvRepository.instance.getCvDetails()
}

And then observe the changes in Activity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    ...

    liveData= cvViewModel.getNewsRepository()
    liveData?.observe(this, Observer { items ->
         //Do your operation here
    })
}
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46