当使用registerForActivityResult启动另一个活动时,Android应用程序将退出



我有两个类MainActivity和EditActivity。我尝试在MainActivity中使用registerForActivityResult((启动EditActivity,但应用程序立即退出;startActivity((运行良好,但registerForActivityResult((符合我的目的,它将结果返回给MainActivity。启动EditActivity的函数如下所示。

主要活动.kt

fun launchEditView(position: Int) {
val getResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if(it.resultCode == Activity.RESULT_OK){
val value = it.data?.getStringExtra("alternative")
listOfTasks.set(position, value.toString())
adapter.notifyDataSetChanged()
saveItems()
}
}
// first parameter is the context, second is the class of the activity to launch
val intent = Intent(this, EditActivity::class.java)
intent.putExtra("taskName", listOfTasks.get(position))
getResult.launch(intent)
}

更新:错误为

java.lang.IllegalStateException: LifecycleOwner com.example.simpletodo.MainActivity@3a90598 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
at androidx.activity.result.ActivityResultRegistry.register(ActivityResultRegistry.java:123)
at androidx.activity.ComponentActivity.registerForActivityResult(ComponentActivity.java:682)
at androidx.activity.ComponentActivity.registerForActivityResult(ComponentActivity.java:691)
at com.example.simpletodo.MainActivity.launchEditView(MainActivity.kt:86)

当您看到logcat时,问题是您试图在错误的状态下注册。您必须在活动状态变为恢复状态之前执行此操作。因此,要解决这个问题,您必须在活动的onCreate方法中注册并持有启动器实例。然后,任何时候你想开始另一个活动,你都可以使用它

lateinit var launcher: ActivityResultLauncher
override fun onCreate(savedInstanceState: Bundle?) {
//The common logic of onCreate method
val launcher= registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if(it.resultCode == Activity.RESULT_OK){
val value = it.data?.getStringExtra("alternative")
listOfTasks.set(position, value.toString())
adapter.notifyDataSetChanged()
saveItems()
}
}
}
fun launchEditView(position: Int) {
val intent = Intent(this, EditActivity::class.java)
intent.putExtra("taskName", listOfTasks.get(position))
launcher.launch(intent)
} 

相关内容

  • 没有找到相关文章

最新更新