I am trying to fetch contacts and show it in a list. I am using RxPermissions for that. The problem here is when I first allow the permission the view returns null and shows empty list even though the list has items in it. But when I go back to the previous activity and come back it works fine.
ContactsFragment.kt
override fun onResume() {
super.onResume()
if (isPermissionGranted) {
Timber.d("Permission is granted")
contactsPresenter.fetchContacts(context)
noPermissionsWarning.visibility = View.GONE
} else {
noPermissionsWarning.visibility = View.VISIBLE
showContactList(ArrayList()) // Show empty list when permissions not granted
}
}
private fun askPermissions() {
rxPermissions
.request(android.Manifest.permission.GET_ACCOUNTS,
android.Manifest.permission.READ_CONTACTS,
android.Manifest.permission.WRITE_CONTACTS)
.subscribe { permissionGranted ->
isPermissionGranted = permissionGranted
}
}
override fun showContactList(selectedContacts: ArrayList<Contact>) {
contactAdapter = ContactListAdapter(selectedContacts, this, context)
val layoutManager = LinearLayoutManager(this.context)
contactsRecyclerView?.layoutManager = layoutManager
contactsRecyclerView?.addItemDecoration(DividerItemDecoration(
contactsRecyclerView?.context,
DividerItemDecoration.VERTICAL
))
contactsRecyclerView?.adapter = contactAdapter
}
ContactsPresenter.kt
override fun takeView(view: ContactsContract.View, context: Context?) {
super.takeView(view)
contactList.clear()
tempContactList.clear()
}
override fun fetchContacts(context: Context?) {
contactManager.getContacts(context)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
it.let {
tempContactList.addAll(it.sortedWith(compareBy { it.userName }))
contactList.addAll(it.sortedWith(compareBy { it.userName }))
view?.showContactList(contactList)// this view is null at first
}
}, {
}).addDisposableTo(disposable)
}
What would I be missing here.
Thank you