“Well begun is half done”. This small sentence tells us a lot. So a good start is very important for achieving success or any of the good finish work. If you are an android developer and want to develop a good application you should follow good android architecture. There are many android architectures, but which one is best for our application? We will clear out your all doubts.
Before we start with MVVM we will discuss some key points and why MVVM. Day-to-day technology is growing faster and trying to make our life easier. Nowadays Android is the very famous mobile operating system developed by Google.
To keep scalability, easy to maintain, easy to test, and clean code you have to follow good architecture. Android provides much Architecture from starting onwards. Following are architecture patterns,
For making an android app you have to follow any one of them, but for good quality of the product at the end, you have to choose a better one. We will describe all patterns one by one in brief and in detail about MVVM.
In short, we can say MVC is the default pattern where an Activity acts as a controller and XML files are view.
Model – is the data layer, responsible for managing the business logic and handling network or database API.
View – is the UI layer which is showing data from the Model.
Controller – contains all the logic and gets notified by user action and updates the model as needed.
At the initial time of android development we used MVC but because of increased complexity, the inefficiency of data access in view and the difficulty of using this pattern in modern UI, android found new architecture is MVP.
The MVP pattern allows separating the presentation layer from the logic and the presenter knows about the view and view knows about the presenter. They interact with each other through an interface.
Model – is the data layer, responsible for managing the business logic and handling network or database API.
View – is the UI(Activity, fragment, etc.) layer working the same as like in MVC? The view will contain a reference to the presenter.
Presenter – is responsible to act as the mediator between view and model. It retrieves data from the model and provide it to the view.
MVP pattern is good for achieving clean code and you can do asynchronous calls via the interface. This is great for testing and modularization. In MVP view is dumb and the presenter almost takes care of everything so it will become complicated and it may produce more classes and java code. In MVP the relationship between view and presenter is one to one.
Model – contains a logic part related to the data of our application. Like POJO, database, network API, etc.
View – is like the same as other architecture, which is the layout of the screen which contains widgets and lots of other views.
ViewModel – is the main part of this architecture. It works as a link between the other two modules. It provides data from the model to view and always provides callbacks to view for updating the status. We can also call it`s an object which defines the behavior of View.
Important things In MVVM are:
Finally, we can say that the concept of MVVM is to separate presentation logic from business logic Which will give us a big result.
There are many benefits of MVVM. Let’s see one by one.
In MVVM, the main part is ViewModel, which is handling your almost business logic using live data and no more interface or other dependency is required. Using all the above features we can achieve the following results:
As we discuss previously MVVM, there are main three components of MVVM architecture. Binder is also an important part of this structure which is very helpful for binding and synchronizing of ViewModel and views with each other.
Model – acts as a data layer that represents the state content. It holds the information. The key point to remember here is model keep always clean. The room is the database for storing the data and it is a persistence library that is able to use live data.
View – is your activity, fragment or any other class which represents the widgets. Using data binding view is forward the callback of the user’s interaction to the ViewModel. Here data binding is a link between view and ViewModel. In MVVM, ViewModel reduces the work of view, which means now you have to write all the logic into ViewModel.
View model – is a state of the data which is stored in the model. ViewModel has a binder for communication between view and model. This automated binding functionality is to keep MVVM to unique from other architecture like MVP and MVC.
Binder – is a mark-up language which makes the developer’s job easy. Using other architecture you have to write more boilerplate code, but the binder has reduced this logic to synchronize the between view and ViewModel.
Live data – is the component which is helpful to remove view dependency. It is an observable data holder class which aware of the lifecycle.
Using Data binding we can reduce our lots of boilerplate Syntex and unrelated binding code like we are using findviewbyid. We can say No more findViewByIds in MVVM using data binding. This is supported by two-way data binding. Rather than programmatically you can bind your data with UI elements into your layouts. Let see how to use binding in the next point with a full code example.
Using one small example of code we will implement MVVM architecture. Using email and password we will do login through Web API. For that we have to follow some basic steps given below.
First of all, create a new android project name “MvvmDemo” and give the package name “com.mvvm_demo”.
Before you start you have to enable the data binding using the below syntax into your app-level build.gradle file inside the android tag.
android{
dataBinding {
enabled = true
}
.
.
.
}
Now make pojo class for login data as VoLoginData.java
public class VoLoginData {
private String success;
private String message;
private String status_code;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus_code() {
return status_code;
}
public void setStatus_code(String status_code) {
this.status_code = status_code;
}
}
To enable binding function into layout, you have to add <layout> tag to the root element of your layout, and for setup data you have to add <data> tag and <variable> tags. Finally your layout look like as below.
activity_main.xml
<layout 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”>
<data>
<variable
name=”loginViewModel”
type=”com.mvvm_demo.viewModels.LoginViewModel” />
</data>
<LinearLayout
android:id=”@+id/activity_main_ll_main”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_centerVertical=”true”
android:layout_gravity=”center”
android:gravity=”center”
android:orientation=”vertical”>
<android.support.design.widget.TextInputLayout
android:id=”@+id/activity_login_input_email”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>
<android.support.design.widget.TextInputEditText
android:id=”@+id/activity_main_tie_email”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:layout_margin=”10dp”
android:gravity=”center”
android:hint=”email”
android:inputType=”textEmailAddress”
android:maxLines=”1″
android:padding=”7dp”
android:singleLine=”true”
android:text=”@={loginViewModel.strUsreName}”
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id=”@+id/activity_main_input_password”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>
<android.support.design.widget.TextInputEditText
android:id=”@+id/activity_login_tie_password”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_margin=”10dp”
android:gravity=”center”
android:hint=”password”
android:inputType=”textPassword”
android:maxLines=”1″
android:padding=”7dp”
android:singleLine=”true”
android:text=”@={loginViewModel.strPassword}”
/>
</android.support.design.widget.TextInputLayout>
<TextView
android:id=”@+id/activity_login_screen_txt_login”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:gravity=”center”
android:padding=”8dp”
android:onClick=”@{(v) -> loginViewModel.onClickLogin()}”
android:text=”@string/login”/>
</LinearLayout>
</layout>
There is some naming convention rules for binding data to the layout. If your XML layout name is activity_main.xml where you enable data binding, the binding class name will be ActivityMainBinding. First and after “”(slash) first later should be Capital, “”(slash) will be remove and Binding suffix will be added in last.
Now in oncreate method of your activity, the syntax of binding class will be as below.
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
Now once you complete binding, next you have to craete ViewModel class for setup data to xml and here ViewModel is mediator between view and model.
public class LoginViewModel extends ViewModel {
public MutableLiveData < String > strPassword = new MutableLiveData < > ();
public MutableLiveData < String > strUsreName = new MutableLiveData < > ();
private MutableLiveData < VoLoginData > userMutableLiveData;
public LoginViewModel() {}
public LiveData < VoLoginData > () {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData < > ();
}
return userMutableLiveData;
}
public void onClickLogin() {
showWait();
Map < String, String > mHashMap = new HashMap < > ();
mHashMap.put(“email”, strUsreName.getValue());
mHashMap.put(“password”, strPassword.getValue());
YourServiceClassHere.userLogin(mHashMap, new MyService.ServiceCallback < VoLoginData > () {
@Override
public void onSuccess(VoLoginData mVoRegister) {
removeWait();
onResponseSuccess(mVoRegister);
}
@Override
public void onError(Exception networkError) {
removeWait();
onResponseSuccess(null);
}
});
}
private void onResponseSuccess(VoLoginData mVoLoginResponses) {
userMutableLiveData.setValue(mVoLoginResponses);
}
public VoLoginData getLoginData() {
return userMutableLiveData.getValue();
}
}
After creating, the ViewModel class initialize it into activity class and do all the logic task there, and in the activity just show the result into UI. You can find the implementation of ViewModel in below class.
ActivityMain.java
public class ActivityMain extends BaseActivity {
LoginViewModel mLoginViewModel;
ActivityMainBinding mActivityMainBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
mActivityMainBinding.setLoginViewModel(mLoginViewModel);
mActivityMainBinding.setLifecycleOwner(this);
mLoginViewModel.getUser().observe(this, new Observer < VoLoginData > () {
@Override
public void onChanged(@Nullable VoLoginData mVoLoginResponse) {
if (mVoLoginResponse != null) {
if (mVoLoginResponse.getSuccess() != null && mVoLoginResponse.getSuccess().equalsIgnoreCase(“1″)) {
//you will be notify here from viewmodel class while you get response from service
//do whatever you want
}
}
}
});
}
}
While you set the ViewModel into a binding object you have to remember some naming conventions, Like first letter is capital of variable name after using “mActivityMainBinding.set”
Like, mActivityMainBinding.setLoginViewModel(mLoginViewModel);
In this syntext “setLoginViewModel” is the name of variable define into xml inside data tag,
<data>
<variable
name=”loginViewModel”
Here we call login API into a view model, we take on click event into XML, using the reference of ViewModel. Once we get the result from the service we set it into (here userMutableLiveData is an object of LiveData) MutableLiveData. Now this observable LiveData notify to our activity where we implement it(mLoginViewModel.getUser().observe()).
Now you can imagine how easy it’s. You will not find any findviewbyid or any boilerplate code into activity or ViewModel.
After discussing all the points we can clearly say that MVP is using the interface for communication between presenter and view, while MVVM is using observer for communication between ViewModel and view.
In MVVM View not required to request every time to the ViewModel for the latest data, using LiveData observer View register itself and that ViewModel keeps a reference of particular LiveData, now in this scenario if anything is changed into Model data, ViewModel get updated and View get notified of this change automatic.
MVVM and MVP both are better than MVC because both make our application clean and modular. For very simple applications you can use MVC, and using data binding with MVVM makes attractive, less code and has good programming techniques.
If you would like to use an interface MVP is a good pattern. So it depends on you which architecture you want to follow, and which one is best for your application and in which pattern you are good.
If you ask me out of two which is best? My opinion is to try to use MVVM.
We, ”OneClick”, also develop applications using MVVM and in the next blog we are going to implement “Clean Code Architecture”. It’s great feedback from our users after using MVVM. If you are looking for MVVM architect development for your existing or new application development work Contact us. We would love to assist you.
Thank you for reading. Have a good day.
Using dynamic packaging technology, one can encapsulate flights, accommodation, cars,…
In today’s contemporary era of accelerated digital evolution, the importance…
The fact is that in today’s internet environment the only…
This website uses cookies.