1

I'm working on permissions util and I need to check for the permissions inside the class, here is my code:

class PermissionUtils private constructor(private val fragment: Fragment, private val context: Context) {

    private lateinit var callBack: PermissionsListenerCallback
    
    fun requestPermission(@NonNull permission: String, callBack: PermissionsListenerCallback) {
        this.callBack = callBack
        if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) this.callBack.onPermissionGranted()
        else requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    }

   private val requestPermissionLauncher = fragment.registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
       if (isGranted) this.callBack.onPermissionGranted() else showPermissionsDialog()//show customize dialog 
    }

interface PermissionsListenerCallback {
        fun onPermissionGranted()
        fun onPermissionDialogCancel()
    }
}

And after I call requestPermission() I got this error:

Fragment XXX{90e0f42} (046e95ee-443b-4938-ad43-a02f42a90736 id=0x7f0a0310) is attempting to registerForActivityResult after being created. Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).

Any one can help please.

  • 3
    Is there a reason you aren't following the [guide that tells you exactly how to register from a separate class](https://developer.android.com/training/basics/intents/result#separate)? – ianhanniballake Jun 15 '22 at 13:48
  • Have you find any solution – Daxesh Nagar Aug 16 '22 at 16:29
  • @DaxeshNagar, Yes I used the same approach here https://developer.android.com/training/basics/intents/result#separate – Owies AL omari Aug 28 '22 at 12:11
  • @DaxeshNagar,, Also you can check this repository, I pushed my code to it: https://github.com/owiesomari/Android-Permissions-Util – Owies AL omari Aug 28 '22 at 12:13
  • Your issue is very similar to https://stackoverflow.com/questions/68405703/how-to-use-registerforactivityresult-correctly-getting-lifecycleowners-must-ca. I recommend reviewing the answers there as they'll likely resolve your issue too. – Bink Sep 20 '22 at 18:07

1 Answers1

-2

Your util class:

class MyLifecycleObserver(private val registry : ActivityResultRegistry)
        : DefaultLifecycleObserver {
    lateinit var requestPermission: ActivityResultLauncher<String>

    // define a permission request result callback(optional)
    var callback: ((Boolean) -> Unit)? = null

    override fun onCreate(owner: LifecycleOwner) {
        getContent = registry.register("key", owner, RequestPermission()) { granted ->
            // Handle the returned granted
            callback?.invoke(granted) 
        }
    }

    fun requestPermission(permission : String, callback: (Boolean) -> Unit) {
        requestPermission.launch(permission)
        this.callback = callback
    }
}

Your activity/fragment:

class MyFragment : Fragment() {
    lateinit var observer : MyLifecycleObserver

    override fun onCreate(savedInstanceState: Bundle?) {
        // ...
        observer = MyLifecycleObserver(requireActivity().activityResultRegistry)
        lifecycle.addObserver(observer) 
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val selectButton = view.findViewById<Button>(R.id.select_button)

        selectButton.setOnClickListener {
            observer.requestPermission("{replace-your-permission-string}") { granted -> 
                // check request result
            }
        }
    }
}

Reference Get a result from an activity, an official Android guide.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
haizhih
  • 97
  • 1
  • 8
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney Aug 24 '23 at 16:16