I need to send data from one fragment to another and it can't seem to work out. Does anyone have any ideas?
Here are some bits of the code in the MainActivity.kt :
lateinit var movieId: String
fun setMovie(movietitle: String){
this.movieId = movietitle
}
fun getMovie(): String {
return movieId
}
This is in the first fragment:
var movieId: TextView = view.findViewById<EditText>(R.id.TitleId)
(activity as MainActivity).setMovie(movieId.toString())
And this is the fragment where I want to receive the string:
searchMovieByTitle((activity as MainActivity).getMovie())
Is there some other way I can recieve the data?
CodePudding user response:
This has to be one of the most-asked questions about Android on here, because the original design doesn't make it easy to connect things up. You've already landed on a common workaround (coordinating things through the parent activity) but your best option is to start using ViewModels, which is a Jetpack component that abstracts away a lot of the work and the complexity:
This case is never trivial as both fragments need to define some interface description, and the owner activity must bind the two together. In addition, both fragments must handle the scenario where the other fragment is not yet created or visible.
This common pain point can be addressed by using
ViewModelobjects. These fragments can share aViewModelusing their activity scope to handle this communication
(emphasis mine)
So yeah, it simplifies a bunch of stuff, it's recommended as standard, most other stuff you work with uses it, it's a good thing to learn if you're doing Android in the 2020s.
(You probably also want to look at LiveData which would allow you to put a currentMovie object in your ViewModel, which the second fragment can observe. When the first fragment sets it with a movie, the second fragment receives the new value automatically, and can do things like display some info, do a search, or whatever)
