I`m developing a gallery app in kotlin using pixabay api, implementing Android Architecture components and retrofit to interact with the server. the app works fine but when i change the configuration the view model returns null! what is the problem ?
interface PhotoApi {
@GET(context.getString(R.string.api_key))
fun getPhotos(): Call<PhotoList>
}
Retrofit setup
object PhotoRetriever {
val BASE_URL = "https://pixabay.com/api/"
val service: PhotoApi
init {
val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build()
service = retrofit.create(PhotoApi::class.java)
}
}
class MainActivity : AppCompatActivity() {
//var photoList: List<Photo>? = null
lateinit var viewModel: MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this@MainActivity).get(MainActivityViewModel::class.java)
viewModel.getList().observe(this, object :Observer<List<Photo>> {
override fun onChanged(t: List<Photo>?) {
textview.setText(t?.get(1)?.webFormatUrl)
}
})
the view model class
class MainActivityViewModel : ViewModel() {
private val repository: Repository
lateinit var photoList: LiveData<List<Photo>>
val itemsListObservable: MediatorLiveData<List<Photo>>
init {
repository = Repository()
itemsListObservable = MediatorLiveData()
}
fun getList(): LiveData<List<Photo>> {
photoList = repository.getNetworkData()
Log.i("RECEIVED","size is ${photoList.value?.size} from viewModel ")
return photoList
}
}
the Repository class
class Repository {
val photoApi: PhotoApi
var photoList: List<Photo>?
val retlist = MutableLiveData<List<Photo>>()
init {
photoApi = PhotoRetriever.service
photoList = ArrayList<Photo>()
}
fun getItemsListFromWeb() {
photoApi.getPhotos().enqueue(object : Callback<PhotoList> {
override fun onFailure(call: Call<PhotoList>?, t: Throwable?) {
// Log.i("RECEIVED","${t?.message} from repository ")
// retlist.value = null
}
override fun onResponse(call: Call<PhotoList>?, response: Response<PhotoList>?) {
if (response!!.isSuccessful) {
retlist.value = response.body()?.hits
} else {
retlist.value = null
}
Log.i("RECEIVED", "size is ${retlist.value?.size} from repository ")
}
})
}
fun getNetworkData(): LiveData<List<Photo>> {
getItemsListFromWeb()
return retlist
}
}
i have solved the problem, the problem was in retrofit onResponse callback method i remove the else block and everything works fine
before
override fun onResponse(call: Call<PhotoList>?, response: Response<PhotoList>?) {
if (response!!.isSuccessful) {
retlist.value = response.body()?.hits
} else {
retlist.value = null
}
Log.i("RECEIVED", "size is ${retlist.value?.size} from repository ")
}
after
override fun onResponse(call: Call<PhotoList>?, response: Response<PhotoList>?) {
if (response!!.isSuccessful) {
retlist.value = response.body()?.hits
}
Log.i("RECEIVED", "size is ${retlist.value?.size} from repository ")
}