Reputation: 199
I have 2 nav host activities Activity A and Activity B with each their own set of navigation graphs. I want to navigate from FragmentA which is in a nav graph hosted by Activity A to FragmentB which is in a nav graph hosted by Activity B to accomplish that i tried explicit deep linking. However no matter how I am not able to retrieve the argument in FragmentB its always the default value. I am using safe args. What am I doing wrong?
update: it seems the problem starts with a not accessible nav graph. Looking a bit more closely at the Log i realized that NavController logged the following message
Could not find destination com.myapp.app:id/nav_graph_b in the navigation graph, ignoring the deep link from Intent....
the nav graph is hosted by the nav host activity B which is set in setComponentName. Why is the graph not accessible then?
the deeplink
val bundle = Bundle()
bundle.putInt("theIntKey", theInt)
val pendingIntent = NavDeepLinkBuilder(requireContext())
.setComponentName(NavHostActivityB::class.java)
.setGraph(R.navigation.nav_graph_b)
.setDestination(R.id.fragmentB)
.setArguments(bundle)
.createPendingIntent()
.send()
navgraph
<navigation 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:id="@+id/nav_graph_b"
app:startDestination="@id/fragmentC"
tools:ignore="UnusedNavigation">
<fragment
android:id="@+id/fragmentB"
android:name="FragmentB">
<argument
android:name="theIntKey"
app:argType="integer"
android:defaultValue="0" />
</fragment>
<!-- other fragments-->
</navigation>
inside FragmentB
//all of these three methods return always the default value
val theIntFromBundle = requireArguments().getInt("theIntKey")
private val args: FragmentBArgs by navArgs()
requireActivity().intent.extras?.let {
val args = FragmentBArgs.fromBundle(it)
}
Upvotes: 0
Views: 1616
Reputation: 51
// For fragment
If you want to get argument in fragment (in your case FragmentB) then make sure you have that keyName in your nav_graph (in your case theIntKey). Now get it like below
val argValue = arguments?.getInt("theIntKey") // for int, getString() for string
// Your requireArguments().getInt("theIntKey") is also correct. Getting default 0 may indicate that "theInt" is also 0 make sure its not same as default value else code is correct for fragment.
// For Activity
if you want bundle value in activity then you can get it in extra's with a little trick as android encapsulate argument to directly accessible for fragments only so for activity...
val encapsulatedBundle = intent.extras?.getBundle("android-support-nav:controller:deepLinkExtras")
val argValue = encapsulatedBundle.getInt("theIntKey")
You can also get intent of activity inside fragment by :- requireActivity().intent.extras.......
Upvotes: 0