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
}
}