Search code examples
androidkotlinandroid-fragmentsandroid-architecture-navigation

Android Navigation Component and File Chooser


I am using Android Navigation with two fragments "Fragment A" and "Fragment B"

In "Fragment A" I open "Fragment B":

findNavController().navigate(R.id.action_fragmenta_to_fragmentb) 

In "Fragment B" I open a file chooser with startActivityForResult:

val openFileIntent = Intent(Intent.ACTION_OPEN_DOCUMENT)
openFileIntent.addCategory(Intent.CATEGORY_OPENABLE)
openFileIntent.type = "application/json"
val mimeTypes = arrayOf("application/octet-stream")
openFileIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
        
startActivityForResult(
   Intent.createChooser(
   openFileIntent,
   getString(R.string.load_from_file)), 909)

In "Fragment B" when a file has been selected I receive a onActivityResult as expected:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 
   //Do something with data from the file
}

What I do not understand is that I am now seeing "Fragment A" displayed instead of staying in "Fragment B". Am I doing something wrong or is this an issue when using Navigation Component with startActivityForResult? Do anyone have a fix to make the app stay in the fragment where startActivityForResult was called? I have a hard time finding documentation about integrating Navigation Component with Intents that starts processes outside the app (ie. file chooser, caller app).


Solution

  • As hinted in Ians comment on my question I listened to some events in the main activity and programmatically navigated to "Fragment A" under some circumstances. After removing this navigation the app stays in "Fragment B" after picking a file as I would expect.