Second activity not showing on real phone - android

My app works absolutely fine on the emulator. but when i get it to a real phone (tried on multiple: one plus 7t pro running android 10, Samsung M20 running android 10), the second activity doesnt launch at all.
I tried a simple app that just launches a second activity & nothing happens even in this. Im out of ideas on what to do!
Here is my main activity:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun btnClick(view: View){
intent.setClass(this,ViewExpenseList::class.java)
intent.putExtra("Text",findViewById<TextView>(R.id.helloWorld).text.toString())
startActivityForResult(intent,1)
}
}
activity xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/helloWorld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="159dp"
android:layout_marginTop="21dp"
android:layout_marginEnd="164dp"
android:layout_marginBottom="286dp"
android:onClick="btnClick"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/helloWorld" />
</androidx.constraintlayout.widget.ConstraintLayout>
My second activity:
package com.anand.expensetracker
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class ViewExpenseList : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_expense_list)
findViewById<TextView>(R.id.textView).text=intent.getStringExtra("Text") +"asdfghj"
}
}
My android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anand.expensetracker"
android:versionCode="1"
android:versionName="#string/versionName">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".ViewExpenseList"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

try change
intent.setClass(this,ViewExpenseList::class.java)
to
val intent = Intent(this, ViewExpenseList::class.java)

Do it like this below
fun btnClick(view: View){
//Get text from view
val myText = helloWorld.text.toString()
//Launch ViewExpenseList Activity
val intent = Intent(this,ViewExpenseList::class.java)
intent.putExtra("Text",myText)
startActivity(intent)
}

Related

Blank screen on device after running kotlin app

I'm working on a kotlin app that simply display a pop-up when buttons are pressed, but for some reason whenever i run the app all i get is a blank white screen. I've tried so many solutions online all to no avail.
Here's my Main Activity code:
import android.app.AlertDialog
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.popup.R
import com.example.popup.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private var activityMainBinding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.lay_custom_dialog)
title = "POP UP"
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// add the following three lines
activityMainBinding?.btnShowDefaultDialog?.setOnClickListener {
showDefaultDialog()
}
}
override fun onDestroy() {
activityMainBinding = null
super.onDestroy()
}
private fun showDefaultDialog() {
val alertDialog = AlertDialog.Builder(this)
alertDialog.apply {
setIcon(R.drawable.ic_hello)
setTitle("Hello")
setMessage("I just wanted to greet you. I hope you are doing great!")
setPositiveButton("Positive") { _, _ ->
toast("clicked positive button")
}
setNegativeButton("Negative") { _, _ ->
toast("clicked negative button")
}
setNeutralButton("Neutral") { _, _ ->
toast("clicked neutral button")
}
}.create().show()
}
private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
And here's the activity_main.xml file(the button views are displayed on the view pager, but not on the device when run)
\<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"\>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnShowDefaultDialog"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/show_dialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.912" />
<Button
android:id="#+id/btnShowCustomDialog"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/show_custom_dialog"
app:layout_constraintBottom_toTopOf="#id/btnShowDefaultDialog"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.238"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.977" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here's the Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Popup"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
In onCreate() you call
setContentView(R.layout.lay_custom_dialog)
however, you say that the layout file for your Activity is called activity_main.xml. You should be doing this:
setContentView(R.layout.activity_main)

SpeechRecognizer is not available on my android emulator. Kotlin

I am new to android application development and I am trying to create a voice assistant in Kotlin. When I try to use my microphone it seems that my SpeechRecognizer doesn't work. I followed the directions of this video, but when I test my app on emulator it seems that SpeechRecognizer isn't avaiable. I also tried this issue on github, but it didn't help me.
The result is always the same. I always get the text string I wrote in case the SpeechRecognizer.isRecognitionAvailable is not available.
Here is what i have tried to do:
Add all permition to my application from android settings
Enable the microphone from emulator settings
Here is my scrips:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.firstkotlinproject">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.speech.RecognitionService"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.FirstKotlinProject"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#525252">
<TextView
android:id="#+id/textView_to_change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFA500"
android:textSize="24sp"
android:text="Hello"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button_to_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_to_change"
android:textColor="#FFA500"
android:backgroundTint="#000"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity
package com.example.firstkotlinproject
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
private val requestCodeDefoult = 102
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button_to_click.setOnClickListener {
askSpeechInput()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == requestCodeDefoult && resultCode == Activity.RESULT_OK) {
val result :ArrayList<String>? = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
textView_to_change.text = result?.get(0).toString()
}
}
private fun buttonPressed() :Boolean {
var result = false
if (button_to_click.isPressed) {
result = true
}
return result
}
private fun askSpeechInput() {
if (!SpeechRecognizer.isRecognitionAvailable(this)) {
Toast.makeText(this, "Speech recognition is not avaiable!", Toast.LENGTH_SHORT).show()
} else if (!buttonPressed()) {
Toast.makeText(this, "Press the button to speak", Toast.LENGTH_SHORT).show()
} else {
val i = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ITALIAN)
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something...")
startActivity(i)
}
}
}

Playing audio in the background more than one minute on Android

I am in the process of developping an Android app handling audio data, now seeing how to have the audio keep playing when the app is in the background using a service.
At this point I can set a service playing audio, but the problem is that once in the background, it will stop after exactly one minute. I have tried a few things I found on the net and nothing works. I put my code hereafter, that would be great if someone could let me know what I need to change.
Here is the MainActivity.kt file:
package me.soft.myapp
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
private var toggleFlag = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun startHandler(view: View) {
val serviceIntent = Intent(this, TheService::class.java)
startService(serviceIntent)
}
fun stopHandler(view: View) {
val serviceIntent = Intent(this, TheService::class.java)
stopService(serviceIntent)
}
fun toggleHandler(view: View) {
toggleFlag = !toggleFlag
when(toggleFlag) {
true -> view.setBackgroundColor(Color.rgb(0xFF,0x00,0x00))
false -> view.setBackgroundColor(Color.rgb(0x00,0x00,0xFF))
}
}
}
Here is the TheService.kt file:
package me.soft.myapp
import android.R
import android.app.Notification
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.IBinder
import android.provider.Settings
import android.widget.Toast
import androidx.core.app.NotificationCompat
class TheService: Service() {
private lateinit var audioPlayer:MediaPlayer
override fun onCreate() {
super.onCreate()
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val runnable = Runnable {
audioPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI)
audioPlayer?.setLooping(true)
audioPlayer.start()
}
val thread = Thread(runnable)
thread.start() // Stops after one minute when in the background.
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
audioPlayer.stop()
}
}
And just in case this is useful, here is the acticity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/ res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp">
<Button
android:id="#+id/strtBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start"
android:onClick="startHandler"
android:textAllCaps="false" />
<Button
android:id="#+id/stpBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop"
android:onClick="stopHandler"
android:textAllCaps="false" />
<Button
android:id="#+id/bgctgBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BCG Toggle"
android:onClick="toggleHandler"
android:textAllCaps="false" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And also in case this is useful, here is the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="me.soft.myapp">
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="myapp"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.ServiceTry"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TheService" />
</application>
</manifest>
You need to use a foreground service. Background services are killed after 2 minutes if the foreground application isn't using the service.Foreground service can last for a long time unless the phone goes very low on resources. to do that use startForegroundService to launch the service, and have the service's onStartCommand call startForeground as well.

the receiver does not show the message. BroadcastReceiver

**Hello everyone, I'm new to programming. When I press the button, nothing happens, I can't find the error. Please see. On assignment, I need to create a message listener (Receiver) and send text data to it by clicking on a button. Show the received data in Toast. .xml file:
**
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/btn_send_message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
.kt file:
package kg.tutorialapp.homework_47
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val myAction = "kg.tutorialapp.action.MESSAGE"
private val alarmMessage = "Hello world!"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener { sendMessage() }
}
private fun sendMessage() {
val intent = Intent()
intent.action = myAction
intent.putExtra("kg.tutorialapp.broadcast.MESSAGE", alarmMessage)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
sendBroadcast(intent)
}
}
receiver file:
class Receiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "Новое сообщение: " + intent.getStringExtra("kg.tutorialapp.broadcast.MESSAGE"), Toast.LENGTH_LONG).show()
}
}
> manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="kg.tutorialapp.homework_47">
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Homework_47"
tools:ignore="AllowBackup">
<receiver
android:name=".Receiver"
android:enabled="true"
android:exported="true"
tools:ignore="ExportedReceiver">
<intent-filter>
<action android:name="kg.tutorialapp.action.MESSAGE"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try removing android:permission="TODO" from your reciever's manifest declaration.
Refer here

Unable to display an image selected with ACTION_GET_CONTENT

I am trying to display an image selected from the gallery in a image view using ACTION_GET_CONTENT, but it is not working for some reason.
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imgViewTakePhoto"
android:layout_width="270dp"
android:layout_height="400dp"
app:layout_constraintBottom_toTopOf="#+id/btnTakePhoto"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnTakePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Image"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.754" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt:
package com.example.fundamentals
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnTakePhoto.setOnClickListener {
Intent(Intent.ACTION_GET_CONTENT).also {
it.type = "image/*"
startActivityForResult(it,0)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == Activity.RESULT_OK && requestCode == 0){
val uri = data?.data
imgViewTakePhoto.setImageURI(uri)
}
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fundamentals">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I am able to select the image from gallery but it is not being displayed in the image view i.e. imgViewTakePhoto .
I tried searching for answers here, some people said for Android 11 or higher, I have to add an external query to my manifest file but that did not worked either.
This was the query:
<queries>
<intent>
<action android:name="android.intent.action.GET_CONTENT" />
<data android:mimeType="image/*"/>
</intent>
</queries>
I don't think the version of Android is a problem here because I tried it again on Android 9, and it didn't work.
startActivityForResult has been deprecated in favour of newer and modern registerForActivityResult and ActivityResultContracts.
Therefore what you should rather be doing is firstly creating an ActivityResultLauncher like following :
private val getImage = registerForActivityResult(ActivityResultContracts.OpenDocument()) {
it?.let {
imgViewTakePhoto.setImageURI(it)
}
}
and then calling it inside your buttons on click like this :
btnTakePhoto.setOnClickListener {
getImage.launch(arrayOf("image/*"))
}
Note that registerForActivityResult is supposed to be initialised before your activity comes into context due to the actual callback registering process which is why it should be directly instantiated as a variable before onCreate is called. If that is not the case then launching the result launcher would throw some state related exception.
Following is the final code for your MainActivity:
class MainActivity : AppCompatActivity() {
private val getImage = registerForActivityResult(ActivityResultContracts.OpenDocument()) {
it?.let {
imgViewTakePhoto.setImageURI(it)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnTakePhoto.setOnClickListener {
getImage.launch(arrayOf("image/*"))
}
}
}

Categories

Resources