Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Jetpack Navigation library and onActivityResult

I'm trying to migrate an app to the new Navigation Architecture Component that was announced at GoogleIO'18

Suppose I need to use an activity that is normally started with startActivityForResult. This activity comes either from a library or a system activity, so I can't modify it.

Is there any way to include this activity as a destination in the navigation graph and get results from it?

like image 339
Mircea Nistor Avatar asked May 23 '18 12:05

Mircea Nistor


1 Answers

The only solution I have so far is to wrap that activity behind a fragment that catches the result and then presents it to the navigation graph:

class ScannerWrapperFragment : Fragment() {

    private val navController by lazy { NavHostFragment.findNavController(this) }

    override fun onResume() {
        super.onResume()
        // forward the call to ScannerActivity
        // do it in onResume to prevent call duplication from configuration changes
        val intent = Intent(context, ScannerActivity::class.java)
        startActivityForResult(intent, 4304357)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 4304357) {
            if (resultCode == RESULT_OK) {

                val params = Bundle().apply {
                    putString("scan_result", data?.extras?.getString("scan_result"))
                }
                //present the scan results to the navigation graph
                navController.navigate(R.id.action_scanner_to_result_screen, params)

            } else {
                navController.popBackStack()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }

    }

}
like image 158
Mircea Nistor Avatar answered Sep 19 '22 20:09

Mircea Nistor