How to use StartActivityResult() outside activity or fragment?
Started 2 years ago by M R Alam in Programming Language, Kotlin
I am trying to add a camera open function to Extention file but getting an error saying "create function startActivityForResult".
Body
I have a function to open camera by intent, and I am trying to add that function to Extention fuction file but getting an error saying "create function startActivityForResult". So can anyone help how to achieve this ?
private fun imageChooser() {
<span class="hljs-comment">//passing intent.</span>
<span class="hljs-keyword">val</span> i = Intent ()
i.type = <span class="hljs-string">"image/*"</span>
i.action = Intent.ACTION_GET_CONTENT
//Getting error here when i am pasting this code in a different file
called extention function.
startActivityForResult (i, <span class="hljs-number">0</span>)
}
1 Replies
-
To use
startActivityForResult()in a non-activity class you must use the a reference to an activity.Pass the activity as a parameter to the function you are using and use it in the non-activity class:
private fun imageChooser(activity: Activity) { val intent = Intent() activity.startActivityForResult(intent,0) }or activity:
this.startActivityForResult(intent, 0)or fragment:
activity?.startActivityForResult(Intent(), 0) requireActivity().startActivityForResult(Intent(), 0)IMPORTANT
startActivityForResult()is deprecated.Follow this from the official documentation