LiveData || MVVM || Retrofit || Part 1

 

Android Livedata :

MVVM (Model View ViewModel) is the interesting topic in android as it provide a solution to problems, making the app development much easier.In this blog we will use android livedata tutorial with MVVM.

 

Info regarding MVVM is explained in my previous blog so we directly get into the topic android livedata tutorial.

 

Dependencies:

Add life-cycle, recycler-view and retrofit dependencies to project also check for the latest dependency’s .

// lifecycle components

implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.0.0'
// retrofit

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
// recyclerview

implementation 'androidx.recyclerview:recyclerview:1.0.0'

 

Manifest Permissions:

Add internet permission to the manifest file.

<uses-permission android:name="android.permission.INTERNET"/>

 

Android Livedata Project Structure :

Image depicting the flow of project showing the folder structure of android livedata tutorial.

android livedata

 

Json Array :

Providing the json array utilized in the project, you can generate a online json file or use your project related api i am just showing a sample json here for android livedata tutorial purpose.

user.json

{
  "status": "ok",
  "message": "Success",
  "data": [
    {
      "phone": "+91-9876543210",
      "name": "abhi",
      "email": "abhi@gmail.com"
    },
    {
      "phone": "+21-1234567890",
      "name": "mike",
      "email": "mike@gmail.com"
    },
    {
      "phone": "+07-456778912",
      "name": "sam",
      "email": "sam@gmail.com"
    }
  ],
  "error": false
}

 

Model :

Model deals with data that may be from remote api’s or local databases like SqliteDB and RoomDB.

We are dealing with user details so create User, User wrapper classes to parse data.

 

For generating model classes automatically from array

UserWrapper.class :

Wrapper means an outer cover around kind of thing this class consists of the json array related data from which User class is parsed.

import com.google.gson.annotations.SerializedName;

import java.util.List;

@SuppressWarnings("unused")
public class UserWrapper {
    @SerializedName("data")
    private List<User> mData;
    @SerializedName("error")
    private Boolean mError;
    @SerializedName("message")
    private String mMessage;
    @SerializedName("status")
    private String mStatus;

    public List<User> getUser() {
        return mData;
    }

    public void setUser(List<User> data) {
        mData = data;
    }

    public Boolean getError() {
        return mError;
    }

    public void setError(Boolean error) {
        mError = error;
    }

    public String getMessage() {
        return mMessage;
    }

    public void setMessage(String message) {
        mMessage = message;
    }

    public String getStatus() {
        return mStatus;
    }

    public void setStatus(String status) {
        mStatus = status;
    }
}

 

User.class

From UserWrapper we get User class as discussed above and from here we can access the data objects to fetch the values.

import com.google.gson.annotations.SerializedName;

public class User {
    @SerializedName("name")
    private String Name;
    @SerializedName("email")
    private String Email;
    @SerializedName("phone")
    private String Phone;

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getEmail() {
        return Email;
    }

    public void setEmail(String email) {
        Email = email;
    }

    public String getPhone() {
        return Phone;
    }

    public void setPhone(String phone) {
        Phone = phone;
    }
}

 

Network :

We define Retrofit network library and use it to make api calls.

 

RetrofitInstance.class

Create Builder and provide base url you may adjust converter factory according to your usage.

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitInstance {
    private static Retrofit retrofit = null;
    public static RestApiService getApiService() {
        if (retrofit == null) {
            retrofit = new Retrofit
                    .Builder()
                    .baseUrl("https://www.json-generator.com/api/json/get/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit.create(RestApiService.class);
    }
}

 

RestApiService

Make a GET call to fetch user data and then with the help of wrapper class parse the data.

import com.abhishek.livedata.Model.UserWrapper;

import retrofit2.Call;
import retrofit2.http.GET;
public interface RestApiService {
    @GET("bQsLPRKKMi?indent=2")
    Call<UserWrapper> getUserList();
}

 

Repository :

We make the api call using retrofit and process the data in the model provided.

Declaring a mutablelivedata for <List<User>>

private MutableLiveData<List<User>> mutableLiveData = new MutableLiveData<>();

 

set the users data

mutableLiveData.setValue(users);

 

and finally returning the data

return mutableLiveData;

 

import android.app.Application;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.abhishek.livedata.Model.User;
import com.abhishek.livedata.Model.UserWrapper;
import com.abhishek.livedata.Network.RestApiService;
import com.abhishek.livedata.Network.RetrofitInstance;

import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserRepository {
    private ArrayList<User> users = new ArrayList<>();
    private MutableLiveData<List<User>> mutableLiveData = new MutableLiveData<>();
    private Application application;
    public UserRepository(Application application) {
        this.application = application;
    }
    public MutableLiveData<List<User>> getMutableLiveData() {
        RestApiService apiService = RetrofitInstance.getApiService();
        Call<UserWrapper> call = apiService.getUserList();
        call.enqueue(new Callback<UserWrapper>() {
            @Override
            public void onResponse(Call<UserWrapper> call, Response<UserWrapper> response) {

                UserWrapper userWrapper = response.body();
                if (userWrapper != null && userWrapper.getUser() != null) {
                    users = (ArrayList<User>) userWrapper.getUser();
                    mutableLiveData.setValue(users);
                }
            }
            @Override
            public void onFailure(Call<UserWrapper> call, Throwable t) {

                Log.d("ListSize"," - > Error    "+ t.getMessage());
            }
        });
        return mutableLiveData;
    }
}

 

Android livedata part 2 :

For continuation of the android livedata tutorial visit the link provided below

LiveData || MVVM || Retrofit || Part 2

If you are having any queries on android livedata tutorial do let us know in the comment section below.If you like this tutorial do like and share for more interesting updates.

Show Buttons
Hide Buttons