Search code examples
androidnavigationandroid-safe-args

how to pass a value using android navigation if the default value null


I'm using android navigation components with safe args. I set that the argument is null-able and default value as null too.

The problem is when I want to pass any value an error is shown:

required: no arguments
found: Character
reason: actual and formal argument lists differ in length

My fragment XML code:

<fragment
        android:id="@+id/bookListFragment"
        android:name="com.example.bookstory.UI.Fragments.BookListFragment"
        android:label="fragment_book_list"
        tools:layout="@layout/fragment_book_list">
            <argument
            android:name="character"
            app:argType="com.example.bookstory.DAO.Character"
            app:nullable="true"
            android:defaultValue="@null" />
</fragment>

My action:

      <action
            android:id="@+id/action_bookDescriptionFragment_to_bookListFragment"
            app:destination="@id/bookListFragment"
            app:popUpTo="@id/bookListFragment"
            app:popUpToInclusive="true" />

I can't understand what is the problem - when I delete the default value it is OK.


Solution

  • ClassNameDirections.ActionName action = ClassNameDirections.actionName(character); Navigation.findNavController(v).navigate(action);

    As your action id is action_bookDescriptionFragment_to_bookListFragment

      <action
            android:id="@+id/action_bookDescriptionFragment_to_bookListFragment"
    

    Then it can be utilized in this navigate() method version that takes in a NavDirections arg:

    findNavController().navigate(BookListFragmentDirections.actionBookDescrioptionFragmentToBookListFragment()
    

    This won't pass in a value, but to do so:

    As your value is named as character:

     <argument
            android:name="character"
            app:argType="com.example.bookstory.DAO.Character"
            app:nullable="true"
            android:defaultValue="@null" />
    

    Then you can cascade the action with the safeArgs generated setCharacter() method:

    findNavController().navigate(BookListFragmentDirections.actionBookDescrioptionFragmentToBookListFragment()
                        .setCharacter("c")
    

    I see that you use safeArgs, but just in case you don't want to use it; you can use this navigate() method version to set the value through a bundle object