Android ViewModel Data Binding Tutorial



Data Binding:
As define in Android developer,


The Data Binding Library is a support library that allows you to bind UI components in your layouts
to data sources in your app using a declarative format rather than programmatically.






Now use data binding on the layout which we created on ViewModel example,
(No any changes in step 1, step 2 and Step 3).
Let us assume, we are showing EMPLOYEE data on screen,
To implement ViewModel,


Step 1:
Create a DataModel class,


public class User {


  public String empId;
  public String empName;
 
  public User(String empId, String empName) {


      this.empId = empId;
      this.empName = empName;
  
  }


  public String getEmpId() {
      return empId;
  }


  public void setEmpId(String empId) {
      this.empId = empId;
  }


  public String getEmpName() {
      return empName;
  }


  public void setEmpName(String empName) {
      this.empName = empName;
  }
}


Step 2:
Create a Repository, which will communicate between ViewModel and Data,


public class MainActivityRepo {


  private static MainActivityRepo instance;
  private ArrayList<User> dataset=new ArrayList<>();


  public static MainActivityRepo getInstance(){
      if(instance==null){
          instance=new MainActivityRepo();
      }
      return instance;
  }


  public MutableLiveData<List<User>> getUser(){
      setUserData();
      MutableLiveData<List<User>> data=new MutableLiveData<>();
      data.setValue(dataset);
      return data;
  }


  private void setUserData(){
      dataset.add(
              new User("emp001","John Doe","http://lorempixel.com/400/200/sports/1/"));
      dataset.add(
              new User("emp002","Ray Ban","http://lorempixel.com/400/200/sports/2/"));
      dataset.add(
              new User("emp003","Don Brown","http://lorempixel.com/400/200/sports/3/"));
  }


Step 3:
Create ViewModel,


public class MainActivityViewModel extends ViewModel {


  private MutableLiveData<List<User>> users;
  private MainActivityRepo mRepo;


  public void init(){
      if(users!=null){
          return;
      }
      mRepo=MainActivityRepo.getInstance();
      users=mRepo.getUser();
  }


  public LiveData<List<User>> getUser(){
      if(users==null){
          users=new MutableLiveData<List<User>>();
      }
      return users;
  }


}


Step 4:
Create a layout xml, with <layout> parent tag,


<?xml version="1.0" encoding="utf-8"?>
<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="empDetail"
 type="com.mpvtest.jetapplication.oneWayBinding.oneWayBinding.dataModel.User"/>
   </data>


<RelativeLayout


      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".oneWayBinding.oneWayBinding.MainActivity">


  <TextView
           android:id="@+id/tv_empId"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
android:text="@{empDetail.empId}"


           />


</RelativeLayout>
</layout>


Now build your project, it will generate DataBinding class,
For eg: if layout name is activity_main, then the generated dataBinding class name will be,
ActivityMainBinding


Step 5:
Create a MainActivity class,
Now remove setContentView,
We have to use DataBindingUtil.setContentView ,
And we will free our code from using findViewById also.


public class MainActivityJv extends AppCompatActivity {


   @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      //setContentView(R.layout.activity_main);


    binding= DataBindingUtil.setContentView(this, R.layout.activity_main);


      MainActivityViewModel model = ViewModelProviders.of(this)
                                      .get(MainActivityViewModel.class);
      model.init();
      model.getUser().observe(this, new Observer<List<User>>() {
          @Override
          public void onChanged(@Nullable List<User> users) {


              changeUI(users);


          }});


  }


  private void changeUI(List<User> user){


/** can get all user data from loop**/
//        for(int i=0;i<user.size();i++){
//         // Log.d("data:value",user.get(i).empId);
//
//        }


 //    TextView tv_empId=findViewById(R.id.tv_empId);
 //   tv_empId.setText(user.get(0).empId);


binding.setEmpDetail(user.get(0));
binding.invalidateAll();


  }
}



Now benefit the data binding.ccc

find the sample project in Github

Comments