티스토리 뷰

Android/Kotlin

[Kotlin]  registerForActivityResult

혀가 길지 않은 개발자 2021. 5. 27. 21:01

startActivityForResult()

onActivityResult()

registerForResultActivity


ActivityResultLauncher<Intent>

registerForActivityResult

ActivityResultContracts.StartActivityForResult()

ActivityResultLauncher.launch(intent)


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">

    <TextView
        android:id="@+id/tv_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        tools:text="Main"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/bt_main" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/bt_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="move to SubActivity"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_main" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_main.xml

 

 

Activity_sub.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/bt_sub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="back"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_sub.xml

 

 

SubActivity.kt

package com.example.registerforresultactivityexample

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton

class SubActivity : AppCompatActivity() {

    private val btSub: AppCompatButton by lazy { findViewById(R.id.bt_sub) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sub)

        btSub.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java).apply {
                putExtra("address", "Seoul")
            }
            setResult(RESULT_OK, intent)
            if (!isFinishing) finish()
        }
    }

}

 

 

 

MainActivity.kt

package com.example.registerforresultactivityexample

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatButton

class MainActivity : AppCompatActivity() {

    private val btMain: AppCompatButton by lazy { findViewById(R.id.bt_main) }
    private val tvMain: TextView by lazy { findViewById(R.id.tv_main) }

    lateinit var activityResultLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btMain.setOnClickListener {
            activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == RESULT_OK) {
                    val address = it.data?.getStringExtra("address") ?: ""
                    tvMain.text = address
                }
            }

            val intent = Intent(this, SubActivity::class.java)
            activityResultLauncher.launch(intent)
        }
    }

}

실행 결과 에러 발생

 

 

 

 

????????

 

 

 

 

에러 발생

onResume() 에서 registerForActivityResult() 호출하면 에러가 발생함.

onCreate() 아니면 onStart() 에서 사용해야 함.

 

 

 

 

 

 

MainActivity.kt

package com.example.registerforresultactivityexample

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatButton

class MainActivity : AppCompatActivity() {

    private val btMain: AppCompatButton by lazy { findViewById(R.id.bt_main) }
    private val tvMain: TextView by lazy { findViewById(R.id.tv_main) }

    lateinit var activityResultLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                val address = it.data?.getStringExtra("address") ?: ""
                tvMain.text = address
            }
        }

        btMain.setOnClickListener {
            val intent = Intent(this, SubActivity::class.java)
            activityResultLauncher.launch(intent)
        }
    }

}

실행 결과

 

 

 

 


에러 발생 시 참고.

https://stackoverflow.com/questions/65121235/fatal-error-lifecycleowners-must-call-register-before-they-are-started-on-regist

 

Fatal error LifecycleOwners must call register before they are STARTED on registerForActivityResult

I have a simple empty activity that checks if permissions need to be requested. When registerForActivityResult is called, it crashes with the error java.lang.IllegalStateException: LifecycleOwner com.

stackoverflow.com

'Android > Kotlin' 카테고리의 다른 글

[Kotlin]  암호화와 복호화  (2) 2021.06.06
[Kotlin]  Lifecycle, LifecycleOwner, LifecycleObserver  (0) 2021.06.05
[Kotlin]  위치 권한  (0) 2021.05.27
[Kotlin]  View  (0) 2021.05.25
[Kotlin] dp와 px  (0) 2021.05.25
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함