Shared ViewModel in Android
Last Updated :
12 Aug, 2024
In Android development, ViewModel serves as a means to facilitate data sharing among different fragments or activities. By utilizing the same ViewModel across multiple fragments, each fragment gains access to the shared data and functionality encapsulated within the ViewModel. This approach offers a streamlined method for enabling communication between various components within an application, a common requirement across most apps.
What will give a deep build in this article?
In this article, we'll dive deep into Shared ViewModel usage in Android for inter-fragment communication. Our focus will be on building an application featuring two fragments. One fragment will be responsible for updating data within a shared ViewModel, while the other fragment will observe these changes and display the updated content on the screen. The application's core functionality revolves around sending, receiving, and displaying messages. A preview GIF is provided below to offer insight into the tasks we'll accomplish throughout this article.
Step-by-Step Implementation
Step 1: Project Creation
Begin by creating a new project in Android Studio. For guidance on how to initiate a new project, please consult the "How to Create/Start a New Project in Android Studio" resource. Ensure that Kotlin is chosen as the programming language.
Step 2: SharedViewModel Class Creation
Navigate to the SharedViewModel.kt file and incorporate the provided code snippet below. This code outlines the structure of the SharedViewModel class. Detailed comments are included within the code to enhance comprehension.
Kotlin
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class SharedViewModel : ViewModel() {
// variable to contain message whenever
// it gets changed/modified(mutable)
val message = MutableLiveData<String>()
// function to send message
fun sendMessage(text: String) {
message.value = text
}
}
Step 3: Fragment Creation
Proceed to create two fragments: MessageSenderFragment and MessageReceiverFragment.
MessageSenderFragment: This fragment is responsible for sending messages to be received by the MessageReceiverFragment. It will feature a button that, upon clicking, will trigger the message sending process.
To implement this, navigate to the MessageSenderFragment.kt file and utilize the provided code snippet below. Detailed comments are included within the code to aid in understanding its functionality.
Kotlin
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.lifecycle.ViewModelProvider
class MessageSenderFragment : Fragment() {
// to send message
lateinit var btn: Button
// to write message
lateinit var writeMSg: EditText
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_message_sender, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// reference for button and EditText
btn = view.findViewById(R.id.button)
writeMSg = view.findViewById(R.id.writeMessage)
// create object of SharedViewModel
val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
// call function "sendMessage" defined in SharedVieModel
// to store the value in message.
btn.setOnClickListener { model.sendMessage(writeMSg.text.toString()) }
}
}
Navigate to the app > res > fragment_message_sender.xml and add the below code to that file. Below is the code for the fragment_message_sender.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/writeMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Write your message"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="100dp"
android:text="Share Your Message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MessageReceiverFragment - To receive the message sent by MessageSenderFragment. It will have a TextView to show the updated message on the screen. Go to the MessageReceiverFragment.kt file and refer to the following code. Below is the code for the MessageReceiverFragment.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
class MessageReceiverFragment : Fragment() {
// to contain and display shared message
lateinit var displayMsg: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// inflate the fragment layout
return inflater.inflate(R.layout.fragment_message_receiver, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// reference for the container declared above
displayMsg = view.findViewById(R.id.textViewReceiver)
// create object of SharedViewModel
val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
model.message.observe(viewLifecycleOwner, Observer {
// updating data in displayMsg
displayMsg.text = it
})
}
}
Navigate to the app > res > fragment_message_receiver.xml and add the below code to that file. Below is the code for the fragment_message_receiver.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textViewReceiver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@color/black"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
We've instantiated the SharedViewModel object, which is shared among fragments due to the fact that they share the same activity as their owner. This is facilitated by utilizing the requireActivity() method within both fragments.
. . .
ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
. . .
Step 3: Update the activity_main.xml
The activity consists of two fragments and is the host for both the fragments.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/receiverFragment"
android:name="com.gfg.article.sharedviewmodel.MessageReceiverFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/senderFragment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="@+id/senderFragment"
android:name="com.gfg.article.sharedviewmodel.MessageSenderFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/receiverFragment" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt remains as it is.
Kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Now, Run the app.
Output:
Source Code: Click Here
Similar Reads
ViewModel With SavedState in Android
Google launched Android Jetpack at Google I/O 2018, which is a bundle of components, tools, and guidelines for creating excellent Android apps. It included LiveData, ViewModel, Room Database, Work Manager, and other components. ViewModel will be discussed in this blog. In the Activity lifecycle, Vie
5 min read
Data Binding with ViewModel in Android
DataBinding is one of the most important concepts to really improve the performance of your Android Application It plays a vital role in the maintenance of the many Android Architectures. In this article, we will learn about DataBinding in ViewModel In Android. Benefits of integrating Data binding i
5 min read
Android View Hierarchy
A block of the screen which is responsible for the UI of the application is called a View. An android app UI consists of views and ViewGroups. View refers to android.view.View class of android, with the help of this class all the other GUI elements are drawn. It is responsible for drawing and event
3 min read
Sharing Shortcuts in Android
With the release of Android Q and its amazing features, it also introduced Sharing Shortcuts. In Q, the Direct Share API has been superseded with the Sharing Shortcut API. Receiving Data from Simple Ends An app can not only transmit data to other applications, but it can also receive data from other
3 min read
onTextChangedListener in Android
onTextChangedListener is a method that is called when text is edited or changed inside an EditText. TextWatcher is an essential class provided by Android Developers. Input text fields can be analyzed with it, and data on other views can be updated immediately. It can be helpful for providing instant
4 min read
What is onMeasure Custom View in Android?
In Android, there are many views available already, using them any developer creates a UI of an android application, that a developer wants to create. In-Built Views are the following: 1. TextView A user interfaces element that displays text to the user. XML <!-- TextView in XML --> <TextVi
3 min read
Android Studio Main Window
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrainsâ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps, such as: A blended environment where one can
4 min read
ViewModel in Android Architecture Components
ViewModel is part of the android architecture component. Android architecture components are the components that are used to build robust, clean, and scalable apps. Android architecture components hold some classes to manage UI components and Data persistence. The ViewModel class is designed to stor
5 min read
View Binding in Android Jetpack
View Binding is one of the best features in Android that allows views to bind seamlessly with an ongoing activity. It replaces the traditional findViewById()method, significantly reducing boilerplate code by automatically generating instances of views for the current layout. One of its most importan
3 min read
Storage System to Store Data in Android
We employ some form of storage in Android to retain the data permanently (until destroyed) for future reference. Android Storage System is the name given to these storage systems. Internal storage, external storage, shared preferences, database, and shared storage are some of the storage options off
5 min read