Fragment not attached to an activity.
TurKurT656 opened this issue · 1 comments
TurKurT656 commented
Description
Because the extension function on Fragment is basically a delegation to FragmentActivity ktx function with requireActivity()
, when Im trying to declare the request in fragment as a property and send the request whenever I need, it throws this Exception: IllegalStateException("Fragment SearchFragment not attached to an activity.")
.
KPermissions version:
3.2.1
API level:
All
How to reproduce it:
- declare the request as a property of Fragment
- call
request.send()
Sample code:
class SearchFragment : Fragment() {
private val permission = permissionsBuilder(Manifest.permission.CAMERA).build().apply {
addListener {
handlePermission(it)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button.setOnClickListener {
permission.send()
}
}
}
fondesa commented
Unfortunately permissionsBuilder()
is available only when the activity is created. So also in the activity, you should not initialize it in the constructor.
You can move the initialization in onViewCreated()
or use by lazy
to initialize it the first time it is used.