Search code examples
androidparcelableandroid-architecture-navigation

Safe Args: use list of parcelables


I am using the Safe Args plugin with the new Navigation components for my Android project. Now I have an argument that is an array list of parcelables, is there a way to use this with the Safe Args Plugin?

Something like app:argType=ParcelableArray. This should be possible since there are bundle methods like putParcelableArrayList().


Solution

  • Currently i don't think there is a simple way to use list of parcelables with safe args, But i have found some "hack" to make this work. For example, i have object 'User' and it parcelable, i am declaring a new parcelable object 'Users' that extending ArrayList().

    @Parcelize
    data class User(var name: String, val age: Int): Parcelable
    
    @Parcelize
    class Users: ArrayList<User>(), Parcelable
    

    Now i can set 'Users' as argument in navigation

    <argument
          android:name="users"
          app:argType="com.navigation.test.Users"/>
    

    And passing array list of parcelables between destinations:

     val user=User("Alex", 36)
     val users= Users()
     users.add(user)
     val action=MainFragmentDirections.actionMainFragmentToSecondFragment(users)
     NavHostFragment.findNavController(this@MainFragment).navigate(action)
    

    And to retrieve them on other destination:

    val users=SecondFragmentArgs.fromBundle(arguments).users
    val user=users[0]
    txtViewName.text=user.name
    txtViewAge.text="${user.age}"
    

    Update:

    Support to list of objects coming in alpha8: https://issuetracker.google.com/issues/111487504


    Update 2: The approach mentioned above will not work in case the activity is recreated, as @Parcelize will not be able to store/restore the list.

    The object will be store in the state bundle, however, it will store an empty list of objects.