相关文章推荐

// Tutorial //

Android MVVM LiveData Data Binding

Published on August 3, 2022
Default avatar

By Anupam Chugh

Android MVVM LiveData Data Binding

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

We’ve already implemented MVVM using Data Binding and covered LiveData and Data Binding in separate tutorials. Today, we’ll use LiveData with Data Binding in our MVVM Android Application. We’ll see how LiveData makes it easy to update the UI from the ViewModel.

MVVM LiveData Data Binding

Getting Started

Project Structure

android-mvvm-livedata-databinding-project The LoginViewModelOld file would contain the old code and LoginViewModel file would contain the refactored code.

Model

Layout

ViewModel

TextInputLayout bindables are updated.

ObservableField isn’t lifecycle aware.

The MainActivity.java class is given below:

package com.journaldev.androidmvvmdatabindinglivedata;
import android.arch.lifecycle.Observer;
import android.databinding.DataBindingUtil;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.journaldev.androidmvvmdatabindinglivedata.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        LoginViewModel loginViewModel = new LoginViewModel();
        binding.setLoginViewModel(loginViewModel);
        loginViewModel.getUser().observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable User user) {
                if (user.getEmail().length() > 0 || user.getPassword().length() > 0)
                    Toast.makeText(getApplicationContext(), "email : " + user.getEmail() + " password " + user.getPassword(), Toast.LENGTH_SHORT).show();

In the above code, the observe method looks for changes in the User object that was contained in the MutableLiveData. It displays a toast with the username and password. Now, let’s replace the ObservableField with LiveData completely.

Refactoring ObservableField to LiveData

android mvvm live data data binding demo As you can see, the Toast message isn’t shown when the user leaves the application. Since the LiveData is lifecycle aware. When you open the application again, the toast would be displayed. This brings an end to this tutorial. You can download the project from the link below:

AndroidMVVMDataBindingLiveData

Github Project Link

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Anupam Chugh

author

Still looking for an answer?

Ask a question Search for more help

Was this helpful?
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 26, 2021

Hello:) Thank you for your tutorials. I have a question to you: How can I add a spinner with mvvm ? I am looking up to internet but I can not understand. Can You help me?

- Esra Didem

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 14, 2019

Please make tutorial on mvvm rx java . Waiting for your tutorial

- Muhammad Zawawi Bin Manja

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 10, 2019

clear explanation…thank you…continue your good work…

- kajendhiran

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 31, 2019

Hi, the tutorial is fantastic and thanks a lot for this. However, I have a query though - In demonstrating the liveData example you had written this piece of code :- User user = new User(email.getValue(), password.getValue()); This code however violates the principle of Dependency Injection. What you be your recommendation to deal with this? Thanks in advance.

- Akash Biswas

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 18, 2019

why use mutablelivedata binding two way instead of livedata?

- Nam Anh

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 11, 2019

Found data binding errors. ****/ data binding error ****msg:Cannot find the getter for attribute ‘android:text’ with value type java.lang.String on com.google.android.material.textfield.TextInputLayout. file:D:\Android\MyBoond\app\src\main\res\layout\activity_registration.xml loc:71:12 - 95:67 ****\ data binding error **** I am getting this error. If anyone can help me. I am newbie in databinding.

- Faheem

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 23, 2019

> busy.setValue(8); //8 == View.GONE You can safely use View class as your ViewModel class is any accessing Android framework classes. JVM based testing will not be run here. > public boolean isEmailValid() { > return Patterns.EMAIL_ADDRESS.matcher(getEmail()).matches(); > } Model class should not access Pattern class as it is based on android framework. MVVM was originally created to help unit test pieces.

- Rohit Sharma

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 11, 2019

Will you have example MVVM databinding to display item in recycler from api and on item click display details of item

- sagar hudge

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 25, 2019

I read regarding MVVM integration with LiveData your article is very useful for me, I hope this article is useful every MVVM beginner who wants to understand very initial level… Thank you so much

- Ram Bhawan

 
推荐文章