startActivityForResult失效,以及registerForActivityResult使用闪退、奔溃问题

在学第一行代码第三版的时候,向下一个Activity传递数据时,说用startActivityForResult

startActivityForResult被抛弃了,查了一下,发现要用registerForActivityResult

button1.setOnClickListener {
            val intent = Intent(this, SecondActivity::class.java)
            val startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
                it -> when(it.resultCode) {
                    Activity.RESULT_OK -> {
                    val return_data = it.data?.getStringExtra("data_return")
                    Log.d("FirstActivity", "return data is $return_data")
                }else -> {

                    }
                }
            }
            startActivity.launch(intent)
        }

但是一点击按钮就出问题,程序就闪退了
显示问题

FATAL EXCEPTION: main
java.lang.IllegalStateException: LifecycleOwner com.example.activatetest.FirstActivity@f60f224 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.

但一直搜第一行,第二行和后面很多一样导致没看到,搜了都是差不多教怎么使用新的registerForActivityResult
后面注意到这个,以及前面搜的时候有人说,要在OnCreate的时候不能在OnStart
一开始还以为我这个button1以及是Oncreate里面了,没想到这样是不行的,要放在外边

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_layout)
        val startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
                it -> when(it.resultCode) {
            Activity.RESULT_OK -> {
                val return_data = it.data?.getStringExtra("data_return")
                Log.d("FirstActivity", "return data is $return_data")
            }else -> {

            }
        }
        }
        .... 
        ....

        button1.setOnClickListener {
            val intent = Intent(this, SecondActivity::class.java)
            startActivity.launch(intent)
        }
}

这样程序就没问题了

posted @ 2022-03-14 15:14  一无所知小白龙  阅读(2281)  评论(0编辑  收藏  举报