Let us begin by considering what android architectures existed before MVVM. The first component is Model View Presenter. Though this architecture classifies the business logic from the app’s UI, it is difficult to implement.
In the long run, this can change into high development costs. The second android architecture is MVC. Just like MVP, it is also quite difficult and not suitable for small projects. Google introduced MVVM to resolve these challenges. By separating code into smaller chunks, MVVM simplifies the debugging process.
Through this article, you’ll understand MVVM architecture and implementation. This blog shows how to debug common mistakes resulting from this architecture.
What is MVVM?
The Model is somewhat the same as MVC. we have ViewModels which are going through the view and all the logic is in the ViewModel and no controller is there.
Example: Knockout.js
What is Kotlin?
Kotlin is a static object-oriented programming language that is interoperable with the Java virtual machine, Java libraries and the android.
Kotlin saves time for programmers as the less verbose language provides briefer and less redundant code. Kotlin can be compiled into a javascript text or an LLVM encoder. In many ways, Kotlin is considered a replacement Java. While it is not compatible with code, it is interoperable with Java code and libraries. Kotlin also has its libraries that were built with its community's early development through an API for Android apps.
How to implement MVVM architecture in Android using Kotlin?
- The first step is to launch Android studio
- The next step is to create the model
- The next step is to create the view
- The next step is to create a recycle view adapter
- The next step is to create the view model
- The next step is to create the view model factory
- The next step is to main activity connecting the code
- The Final is the result
How to launch Android Studio?
First Launch Android Studio and create a new project. Make sure that you select Kotlin as your programming language.
How to Create the model?
Next is to create the app model. Also referred to as the data class. To avoid misunderstanding, create a package named model inside the java folder. Then, create a class named Blog in the model package.
For simplicity, the class will only have one variable. There is no need to include getters and setters, Kotlin adds them to the class automatically.
Here’s the code for the class.
data class Blog(var title: String)
How to Create the View?
The view is what the user displays. The User interface, therefore, needs to be well structured to simplify any confusion and dissatisfaction.
Open the activity_main.xml
file and change the Layout from a linear Layout. Set the orientation to vertical, this arranges the User interface components vertically in the Layout. Our app’s first-ever widgets are Edittext, Button, and a RecyclerView.
Make sure all these steps have IDs since they will be vital at a new stage.
How to Create the item_view?
In the Layout, we need to build the design of the element in the RecyclerView. Therefore, build a file named item.xml and include the code sufficient code. The design is easy since the individual can also access one attribute from the data class.
How to Create a RecyclerView Adapter?
A RecyclerView adapter handles the linking of the item.xml layout to the RecyclerView. It also includes a list of items and displays them to the user. The code for the RecyclerView is shown below.
class NoteRecyclerAdapter(val viewModel: MainViewModel, val arrayList:
ArrayList<Blog>, val context: Context):
RecyclerView.Adapter<NoteRecyclerAdapter.NotesViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): NoteRecyclerAdapter.NotesViewHolder {
var root =
LayoutInflater.from(parent.context).inflate(R.layout.item,parent,false)
return NotesViewHolder(root)
}
override fun onBindViewHolder(holder: NoteRecyclerAdapter.NotesViewHolder,
position: Int) {
holder.bind(arrayList.get(position))
}
override fun getItemCount(): Int {
if(arrayList.size==0){
Toast.makeText(context,"List is empty",Toast.LENGTH_LONG).show()
}else{
}
return arrayList.size
}
inner class NotesViewHolder(private val binding: View) :
RecyclerView.ViewHolder(binding) {
fun bind(blog: Blog){
binding.title.text = blog.title
binding.delete.setOnClickListener {
viewModel.remove(blog)
notifyItemRemoved(arrayList.indexOf(blog))
}
}
}
}
How to Create the ViewModel?
Create a package ViewModel. Inside this file, built a Kotlin class and name it MainViewModel. The class should extend the Android ViewModel. You might face failure if you failed to include lifecycle dependencies from Jetpack.
The MainViewModel will have mutable live data that holds the array list. It’s vital to use LiveData since it notifies the UserInterface in case of any data change. The MainViewModel is shown below.
class MainViewModel: ViewModel() {
var lst = MutableLiveData<ArrayList
How to Create the ViewModel Factory?
The purpose of a ViewModel factory is to the ViewModelchange. This prevents the app from destroying in case an activity is not found.
The syntax for our MainViewModelFactory is shown below:
class MainViewModelFactory(): ViewModelProvider.Factory{
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if(modelClass.isAssignableFrom(MainViewModel::class.java)){
return MainViewModel() as T
}
throw IllegalArgumentException ("UnknownViewModel")
}
How is MainActivity connect the code?
We have built the model, ViewModel, ViewModelfactory, and RecyclerView. These variables need to be instantiated in the MainActivity for the application to execute.
Beginning by showing the RecyclerView and instantiating it. Set out the layout manager for the RecyclerView to LinearLayoutManager. The MainActivity file contains three major methods: initialiseAdapter,observeData, and addData. the initialiseAdapter method assigns a ViewManager to the RecyclerView.
The observeData looks for changes in the viewmodel and send them to the RecyclerAdapter. The addData method takes in the user’s input and updates the list.
class MainActivity : AppCompatActivity() {
private var viewManager = LinearLayoutManager(this)
private lateinit var viewModel: MainViewModel
private lateinit var mainrecycler: RecyclerView
private lateinit var but: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainrecycler = findViewById(R.id.recycler)
val application = requireNotNull(this).application
val factory = MainViewModelFactory()
viewModel = ViewModelProviders.of(this,factory).get(MainViewModel::class.java)
but = findViewById(R.id.button)
but.setOnClickListener {
addData()
}
initialiseAdapter()
}
private fun initialiseAdapter(){
mainrecycler.layoutManager = viewManager
observeData()
}
fun observeData(){
viewModel.lst.observe(this, Observer{
Log.i("data",it.toString())
mainrecycler.adapter= NoteRecyclerAdapter(viewModel, it, this)
})
}
fun addData(){
var txtplce = findViewById<EditText>(R.id.titletxt)
var title=txtplce.text.toString()
if(title.isNullOrBlank()){
Toast.makeText(this,"Enter value!",Toast.LENGTH_LONG).show()
}else{
var blog= Blog(title)
viewModel.add(blog)
txtplce.text.clear()
mainrecycler.adapter?.notifyDataSetChanged()
}
}
}
What are the Results?
If there were no mistakes in your code, it should compile and show the User interface in the image below. Whatever you type in the EditText should display in the recycler view once you select the submit button.
If you have any doubts about the above topic or have to get services and consultations and get MVVM architecture and android development using Kotlin. Feel free to contact us. AIRO GLOBAL SOFTWARE will be your strong digital partner.
E-mail id: [email protected]
Author - Johnson Augustine
Chief Technical Director and Programmer
Founder: Airo Global Software Inc
LinkedIn Profile: www.linkedin.com/in/johnsontaugustine/