Fragment to Fragment Communication Using ViewModel

There are multiple ways to communicate from one fragment to another fragment.

The most used one was an interface also known as inter fragment communication

After the Jetpack component has been introduced ViewModel is very useful in many ways one being sending the data from one fragment to another.

Let's demonstrate it with a very basic example in android studio

I am having 1 activity and 2 fragments, Now fragment 1 wants to send the data let's say some string message to fragment 2 using shared ViewModel.

I am using view bindings for binding the views and navigation components for fragments

In MainActivity

class MainActivity : AppCompatActivity() {

private var _activityMainBinding: ActivityMainBinding? = null
private val activityMainBinding get() = _activityMainBinding!!

//This is the shared view model by which we will communicate
private lateinit var sharedViewModel: SharedViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(_activityMainBinding!!.root)
//Initializing the view model
sharedViewModel = ViewModelProvider(this).get(SharedViewModel::class.java)
}

override fun onDestroy() {
super.onDestroy()
_activityMainBinding = null
}
}

In SharedViewModel

class SharedViewModel() : ViewModel() {

//This is the mutable live data in which we are putting the data
private val msgMLD = MutableLiveData<String>()

//This is msg live data by which we will observe the data in other fragment
val msgLiveData get() = msgMLD

//This is the method which will be called by fragment 1 and will put data in mutalbe live data
fun sendMessage(message: String) {
msgMLD.value = message
}

}

In FirstFrament

class FirstFragment : Fragment() {

private var _fragmentFirstBinding: FragmentFirstBinding? = null
private val fragmentFirstBinding get() = _fragmentFirstBinding!!

//This is the shared view model by which we will communicate
private lateinit var sharedViewModel: SharedViewModel

companion object {
@JvmStatic
fun newInstance() = FirstFragment()
}

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_fragmentFirstBinding = FragmentFirstBinding.inflate(inflater, container, false)
return _fragmentFirstBinding!!.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
/* Initializing the view model with activity reference so that we will have sharedview
model available for both the fragment*/

sharedViewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)

fragmentFirstBinding.btnSendMessage.setOnClickListener {
//Sending the data to the view Model

val message = fragmentFirstBinding.etMessage.text.toString()
sharedViewModel.sendMessage(message)
Navigation.findNavController(fragmentFirstBinding.root)
.navigate(R.id.action_firstFragment_to_secondFragment)
}
}

override fun onDestroy() {
super.onDestroy()
_fragmentFirstBinding = null
}

}

In SecondFragmant

class SecondFragment : Fragment() {

private var _fragmentSecondBinding: FragmentSecondBinding? = null
private val fragmentSecondBinding get() = _fragmentSecondBinding!!

//This is the shared view model by which we will communicate
private lateinit var sharedViewModel: SharedViewModel

companion object {
@JvmStatic
fun newInstance() = SecondFragment()
}

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_fragmentSecondBinding = FragmentSecondBinding.inflate(inflater, container, false)
return _fragmentSecondBinding!!.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
/* Initializing the view model with activity reference so that we will have sharedview
model available for both the fragment*/
sharedViewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
//Here we are observing the changes and showing in the text view of fragment
sharedViewModel.msgLiveData.observe(viewLifecycleOwner) { message ->
fragmentSecondBinding.tvMessage.text = message
}
}

override fun onDestroy() {
super.onDestroy()
_fragmentSecondBinding = null
}

}

Complete code link

https://github.com/Aalishan565/ShareDataInFragments

--

--

--

Senior Android App Developer | Startup | Product base | Java | Kotlin | MVVM | Architecture components | Android Blogger

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Conditional statements

Lightning fast search with ElasticSearch

How to create a Login Application on Android Studio?

How Much Java Do You Need to Know to Get a Job?

How Can Hierarchical Test Structure Absolutely Make a Mess?

Docker basics , installation and configuring , creating containers In RHEL8

Buffer Overflow Overview

Docker 02 / namespace/ watch using tmux

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aalishan Ansari

Aalishan Ansari

Senior Android App Developer | Startup | Product base | Java | Kotlin | MVVM | Architecture components | Android Blogger

More from Medium

Android Room versus SQLite — Which is best?

Understanding and Using Services in Kotlin — Beginner — In-Depth Guide

Enhancing Android App Architecture with Domain Layer

Kotlin Coroutines Basics — Simple Android App Demo