Pass data from single activity to start destination fragment using Architecture Component Navigation

Find a solution,works fine but i don't like it there's must be a better solution for that.

In your Activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val navController = findNavController(R.id.nav_controller_fragment)
    val bundle = Bundle()
    bundle.putString("name","your value")
    navController.setGraph(navController.graph,bundle)
}

In your start Fragment:

  val args: MainFragmentArgs by navArgs()
  textView.text = args.name

In your 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/mobile_navigation"
        app:startDestination="@id/mainFragment">

<fragment android:id="@+id/mainFragment"
          android:name="com.haidar.mediasaver.fragments.MainFragment"
          android:label="main_fragment"
          tools:layout="@layout/main_fragment">
    <argument android:name="name"
              app:argType="string"/>
</fragment>


If you use safe args, you need to do:

  1. Remove the app:navGraph attribute from your NavHostFragment
  2. Then call:

    findNavController(R.id.nav_controller_fragment)
                     .setGraph(
                          R.navigation.nav_graph,
                          MainFragmentArgs("your values").toBundle()
    )