Best practices while using Jetpack in Android

WRITTEN BY

Pooja Kelodia

Senior Android Developer

Give a boost to your codes with Android Jetpack

Developing android apps can be equal parts challenging and rewarding. In my journey as an Android developer, I come across many obstacles on a daily basis while developing an app just like every other developer out there. As the name suggests, Jetpack allows us to jump through these daily obstacles and gives that much needed nitro boost to jumpstart the development process.

What is Jetpack?

Jetpack is a collection of android software components aimed at helping us write high quality apps quickly, even while supporting older versions of the Android OS. Past few years we have witnessed tremendous adoption by apps, from large developer teams to those just getting started.

All the jetpack components are available in Google maven repository. Open the build.gradle file of your project and add the google() repository as shown below:


allprojects {
  repositories {
    google()
    jcenter()
  }
}

AndroidX

AndroidX is a jetpack evolution of the original android support library and it is the open source project that the android developer uses to build, test, and release libraries within jetpack.

Android release 9.0 (API level 28) is a new version of the support library called androidX Which is a part of jetpack. The androidX library also contains the existing support library and also includes the latest android software components. You can also use the old api level (< Api LEVEL 28) with android.support.*

I recommend using the androidX libraries in all your new projects. You should also migrate your existing projects to androidX as well.

AndroidX fully replaces the support library by providing the features and new libraries . In addition androidX includes the following features:

1. All packages in AndroidX starting with string androidx.

2. Unlike the support library , AndroidX is separately maintained and updated. The androidX package version starts with version 1.0.0.

In 2020 only i have started using androidX and believe me the experience was very good. So i would suggest you all to start using androidX.

So it's time to use AndroidX or get stuck with the 28.0.0 support library. Choice is yours.

Why is this necessary?

With the increasing demand for mobile apps, it has become necessary to develop apps as quickly as possible. And creating apps quickly in android is not easy. You need to keep many important points in your mind, have to be aware of the mobile app development lifecycle and also check what impacts changing the code. This entire process requires effort and time and that is why utilities like android jetpack are needed. It helps in quickening the app development without any effect on the quality of the app.

Android jetpack components - Architecture:

1. Data Binding

2. Lifecycle

3. LiveData

4. Navigation

5. Paging

6. Room

7. ViewModel

8. WorkManager

Google introduces Android architecture components to make your app more modular, easy to maintain and test friendly. Most of these libraries are existing however navigation, paging and workmanager are the newest.

ViewModel

ViewModel is the main component of android architecture:

There are three steps to setting up and using viewModel:

1. Separate your data from the UI controller by creating a class that extents ViewModel.

2. Set up communication between UI controller & ViewModel.

3. Use your View Model in your UIcontroller.

Step 1: Create a ViewModel Class: For creating ViewModel, you will first need the lifecycle dependency . See the latest dependency here

https://developer.android.com/jetpack/androidx/releases/lifecycle#declaring_dependencies

You will need to create a ViewModel class for each screen in your app. This view model class will hold all the data associated with the screen and have the getter and setter for the stored data. You can also create a repository to perform all your db, web service operations. So lets create a ViewModel Class for your Login Activity.

We will create a Login example using viewModel.

Before creating a view model class I will create a repository for login api's.


public class LoginRepo {
  private static LoginRepo instance;
  private static ApiInterface apiInterface;
  Call< JsonObject > callLogin;
  private static Activity context;
  private static SettingPreferences settingPreference;

  public static LoginRepo getInstance(Activity mContext) {
    if (instance == null) {
      instance = new LoginRepo();
    }
    context = mContext;
    settingPreference = new SettingPreferences(mContext);
    apiInterface = ApiClient.getClient().create(ApiInterface.class);
    return instance;
  }

  public MutableLiveData< JSONObject > performSendOtp(LoginRequestInfo requestInfo) {
    final MutableLiveData< JSONObject > newsData = new MutableLiveData<>();
    callLogin = apiInterface.sendOtpForCustomerLogin("application/json",requestInfo);
    callLogin.enqueue(new Callback< JsonObject >() {
      @Override
      public void onResponse(Call< JsonObject > call, Response< JsonObject > response) {
        JSONObject jsonObject = null;
        try {
          if (response!=null ) {
            if (response.body()!=null) {
              jsonObject = new JSONObject(response.body().toString());
            }
          }
        } catch (JSONException e) {
          e.printStackTrace();
        } finally {
          if (jsonObject!=null) {
            newsData.setValue(jsonObject);
          } else {
            newsData.setValue(null);
          }
        }
      }
      @Override
      public void onFailure(Call< JsonObject > call, Throwable t) {
        newsData.setValue(null);
      }
   });
   return newsData;
  }

  public void cancelLoginRequest() {
    if(callLogin!=null) callLogin.cancel();
  }
}

Now after that i will create a ViewModel class for login


public class LoginViewModel extends ViewModel {
  private MutableLiveData< JSONObject > mJsonResponseSendOp;
  Activity activity;
  LoginRepo mLoginRepo;

  public void init(Activity mContext) {
    activity = mContext;
    mLoginRepo = LoginRepo.getInstance(activity);
  }

  public void requestToSendOtp(LoginRequestInfo requestInfo) {
    mJsonResponseSendOp = mLoginRepo.performSendOtp(requestInfo);
  }

  public LiveData< JSONObject > responseForSendOtp() {
    return mJsonResponseSendOp;
  }

  public void cancelLoginRequest() {
    mLoginRepo.cancelLoginRequest();
  }
}

Step 2: Associate the UI controller and ViewModel

Your UI controller (Activity or Fragments) need to know about your ViewModel class (LoginViewModel). This is how your UI controller can display the data and update the data when UI interaction occurs, such as pressing a login button to login to your app.

For using ViewModel in your UI controller you need to create a member variable for your ViewModel.

ViewModelProviders.of(< Your UI controller >).get(< Your ViewModel >.class)


@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_login);
  ButterKnife.bind(this);
  mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
  mLoginViewModel.init(this);
}

And then on click of login button just call the mLoginViewModel.responseForSendOtp();

This is how you can use ViewModel & lifecycle in your android application.

Considering that in recent times apps are now expanding their usability into other devices besides smartphones and tablets to wearables, Android Jetpack for app development ultimately leads to smarter, user-friendly apps.Our blogs are designed to help the developer community out there, if you find this blog useful follow us for more updates.

Latest Blogs

Integrating Google map in Angular

Read More

How to install Angular on Mac fvdvdfvdvfvfvd

Read More

Google map styling vdvdfvdvdfvdvfvfvd

Read More