Passing Data Between Fragment Using Navigation Ui Component
Solution 1:
You can do it either way . Both approaches are fine . But since you are passing only one object or want to have only one object in the next Fragment , you should go for safe args pattern . The reason is there will be an overhead added if you just pass the id and then that id will fetch the data . So to remove that it is preferable to use safe args . Also it is easy to maintain the safeArgs process since it most of the time saves your data on activity / fragment being in the background unlike the other wherein you need to call the api / database again . But if your are getting a list of objects based on the id , then you should do it using the passing the id and getting the data from api/database way .
Since you have no where mentioned in your post of getting a list of Data , below is the way of doing it using SafeArgs.
Step 1: Make your data class Parcelable :
@ParcelizedataclassCharacter(
val name: String,
val img: String,
val occupation: ArrayList<String>,
val status: String,
val nickname: String,
val appearance: ArrayList<Int>
):Parcelable
Step 2 : Then in your nav graph you declare an parcelable object to be send to the next fragment as an argument in the nav graph the following way. Select the type as Custom Parcelable and then select your class and also name it as character for better readability in the future .
Step 3 : Now in your fragment , get the data class you want to send and pass it in when you are navigating to the next Fragment .
valaction= SenderFragmentDirections.senderFragmentoRecieverFragment(character )
findNavController().navigate(action)
Step 4 : In the fragment that you are trying to get the args declare a top variable as follows and then in your onCreate() / onViewCreated() get the data .
privateval args by navArgs<ReceiverFragmentArgs>()
overridefunonViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
args.character.whatever
//And do your further needs
}
Remember to setup dependencies correctly in gradle (both app as well as project level)
Post a Comment for "Passing Data Between Fragment Using Navigation Ui Component"