Passing data from Activity to Fragment using Safe Args

Viewed 3770

I have recently started looking into a bit more advanced Android development due to my needs. Starting with Navigation Component, I learned about a way to work with Fragments as well as possibility of passing data with SafeArgs

While I am able to understand and find information on how to pass data between different fragments, I am not finding any information on how to pass data from the actual Activity to the fragment.

Here is a short description of when I would need this:

<- Login Screen -> (Main activity) - NO FRAGMENTS, SIMPLE LOG-IN ACTIVITY

-- user enters data

-- clicks Log-in

-- Login successful

-- Saving and sending HTTP response data with other necessary information and transfering to Profile Page

<- Profile Page -> (ProfilePage Activity) with Drawer Layout that uses NavHostFragment to display different Fragments: [Profile Page], [Contact Info], [Payment Cards]

-- Profile Page Fragment

-- Extract data sent by Main Acitivity and use it to change values of ProfilePage Fragment TextViews

Here is where I face my problem - I have no idea how to pass data from the actual Activity to Fragment, especially when I know that there are so called SafeArgs that I only have a vague undestanding of.

Can someone please help me understand this better or at least point me in the right direction?

1 Answers

yes as you have guessed it you will have to use safe args to have it as a best option.

In the Navigation editor, click on the destination that receives the argument. In the Attributes panel, click Add (+). In the Add Argument Link window that appears, enter the argument name, argument type, whether the argument is nullable, and a default value, if needed. Click Add. Notice that the argument now appears in the Arguments list in the Attributes panel. Next, click on the corresponding action that takes you to this destination. In the Attributes panel, you should now see your newly added argument in the Argument Default Values section.

You can also see that the argument was added in XML. Click the Text tab to toggle to XML view, and notice that your argument was added to the destination that receives the argument. An example is shown below:

 <fragment android:id="@+id/myFragment" >
 <argument
     android:name="myArg"
     app:argType="integer"
     android:defaultValue="0" />

you should consider adding classpaths and pulgins for safe-args.

def nav_version = "2.3.0-beta01"
    classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"

and plugin:

apply plugin: "androidx.navigation.safeargs"

your safe-args will generate classes for you and then pass data this way :

override fun onClick(v: View) {
        val name = textview.text.toString()
        val action = ThisFragmentDirections.ThatFragmentAction(name)
        v.findNavController().navigate(action)
    }

This way you can do this to both activities to fragments or between fragments.

Related