Safeargs library doesnt generate direction class

Solution 1:

Look for the class of the fragment which is the source of navigation. If you define navigation from FragmentA to FragmentB, you will find FragmentADirections class with the actions you defined (in nav_graph.xml) in it.

Then, to generate direction class ( Also argument class) you need to go Project level gradle then click the build command. Here I attached a screenshot to give a clear understanding.

enter image description here

Solution 2:

I forgot to apply plugin in app.gradle file, just add this line

apply plugin: "androidx.navigation.safeargs.kotlin"

or this line if you are using java

apply plugin: "androidx.navigation.safeargs"

Solution 3:

I faced a similar issue working with android studio 4.2 preview.

The issue was that the IDE somehow was not picking the source folders where the generated direction classes where being placed by the plugin. So adding the following to my app build.gradle file resolved the issue for me.

sourceSets {
    main {
        java {
            srcDirs += 'build/generated/source/navigation-args'
        }
    }
}

Hope this helps!

Solution 4:

As Christian wrote, adding source set do app gradle file helped. The problem occurs in Android Studio 4.1 and 4.2 for me. In Kotlin DSL:

android {
    ....
    sourceSets {
        getByName("main").java.srcDirs("build/generated/source/navigation-args")
    }
}

Solution 5:

If all the answers above didn't work for you and you are still having a problem with the directions class not being generated. Make sure you are looking for the right directions class.

For example, we have to pass arguments from FragmentA to FragmentB.
In the navigation graph file, we have to add the <argument/> tag under FragmentB's tag. This way, we will get two generated classes FragmentBArgs and FragmentADirections. As you can see, it is the FragmentA's name who got used for the directions class created, not FragmentB.

So, keep in mind that unlike what this question's user is looking for, the directions class generated will get the class name of the action starter fragment appended with the word "Directions". Not the destination fragment's class name (argument's owner).

Here is what the documentation says:

A class is created for each destination where an action originates. The name of this class is the name of the originating destination, appended with the word "Directions".

A class is created for the receiving destination. The name of this class is the name of the destination, appended with the word "Args".

Also, adding the argument tag under the action tag will not generate a directions class. It's used to give a different default value for the destination fragment's argument.

Hope this helps!