我正在尝试获取联系人并将其显示在列表中。我为此使用RxPermissions。这里的问题是,当我第一次允许该权限时,即使列表中包含项目,该 View 也将返回null并显示空列表。但是,当我返回上一个 Activity 并返回时,它工作正常。
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)
}
我在这里会缺少什么。
谢谢
最佳答案
看起来您应该在此行之后立即获取联系人:
isPermissionGranted = permissionGranted