Posts

Showing posts from 2017

Android Architecture Components meets Data Binding : Lifecycle awareness!

Image
Finally Android Data Binding library got updated to play nice with Android Architecture Components library and became life-cycle aware! This means that any changes to the LiveData objects will be reflected in the layouts... automagically! :) * Tested on Android Studio 3.1 - canary 6 Whats new? To make the binding life-cycle aware you need to pass the life-cycle owner to the ViewDataBinding by calling the  setLifecycleOwner method. The ViewModel: Our view model consists of the LiveData object that is simply and observable data container, where the observer gets notified of data changes. The model: Our model has one field that is used to store user's name. A POJO. The layout: -Out layout consists of a text field that is bound to the user's name. And will be updated when our LiveData container posts a change. -We also have an EditText that is two-way bound to the user's name, meaning when text gets entered, the name is updated and vise-versa, when the use...

Android Lists Made Easy: DataBinding + RecyclerViewBindingAdapter Library

Image
RecyclerViewBindingAdapter Library This library provides a powerful yet reusable RecyclerView adapter that leverages ObservableArrayList and DataBinding to simplify your life. Tell the adapter which layouts your models map to and then just modify your observable list and the adapter takes care of the rest. Its that simple! Check out the library and example app source code here . Step 1: Add  jitpack  repository to you project's  build.gradle file Step 2: Enable Android data binding and add library dependency in the module's build.gradle file that you will be using the library in. You will need data binding to create layouts bound to  ViewModel s . The adapter dynamically creates all the rows and manages recycling of the layouts. Step 3: Create  ObservableArrayList  that will hold all the view models  and  initialize EasyRecyclerAdapter with it. Set up the mappings between the layouts you intend to show in the list ...

Android Architecture Components : ViewModel

Image
ViewModel : UI-Related Data Object One of the biggest challenges for an Android developer is keeping data across configuration changes such as screen rotation or during the recreation of Activity / Fragments after its been destroyed and recreated by the framework. Luckily the new Android Architecture Components library has ViewModel class that is intended to store and manage UI-related data so that the data survives configuration changes.  Benefits Keeps data across UI recreation No need to repeat API calls and Database queries on UI recreation  Keeps  Activity / Fragments clean since work is now delegated to ViewModels Share ViewModels between Fragments Subclass ViewModel To create a view-model just subclass ViewModel . View-models are responsible to provide data and keep reference to it. Our TimerViewModel lazily initializes TimerLiveData which is a LiveData implementation of a timer that counts seconds, read more about TimerLiveData a...

Android Architecture Components : LiveData

Image
Live Data : Life-cycle aware Observables As an Android developer you often have to work with data that is dynamic and changing with user input, device configuration changes, or even time changes. On top of this as a developer you have to respect the life-cycle of an Activity of Fragment that contains this dynamically changing data: stop updates onStop() or onPause() and restart the updates onStart() and onResume() . Examples of this is location data, countdown timers, user's list selections and any other type of dynamically changing data. Lets see how we can make these tasks easier using LiveData . We will demonstrate LiveData by creating a self contained timer. Subclass LiveData LiveData object is set active when the observer's lifecycle is stated or resumed . And the LiveData object is set inactive when the observer's lifecycle is stopped or pause . In our TimerLiveData we start timer when  onActive() is called and stop the timer when  onInactive() ...

Android Architecture Components : Room Persistence Library

Image
Room: a SQLite object mapping library After many years and using countless 3rd party DAO libraries I am happy to finally introduce official Android solution to working with SQLite databases and it is called Room Persistence Library. Before we begin you can find code from this tutorial here . SQL Review Data is stored in tables Table's rows contain entities Table's columns contain entity's fields Rows can have id's (primary keys) and id's must be unique You can create relationships between rows in different tables by referring to other row's id (foreign key) Index primary key columns for performance Use SQL queries to find sort and filter the data from tables What is Room? Room is a library that uses annotations in your Java data models and your data access objects (DAO's) to generate database schema (table definitions) and SQLite queries. So you don't have to write all the SQLite queries from scratch and have logic for storing and r...

Android Data Binding : Dynamic RecyclerView Adapter

Image
One of the most common list design patterns that I encounter as Android developer is a list with a variation of the following: Multiple row types.  Expandable/Collapsible rows or sections.  Load more/Scroll to load more.  Delete rows/Sections.  And all of these can be implemented in a generic manner with Android Data Binding library. You can write one adapter for all the RecycleView s in your app and use it to render all the common design patterns. Check out the source for the example in this tutorial here . Final result: Lets begin by defining our adapter: public class RecyclerViewBindingAdapter extends RecyclerView.Adapter<RecyclerViewBindingAdapter.BindingViewHolder> { private ObservableList<AdapterDataItem> data; public RecyclerViewBindingAdapter(ObservableList<AdapterDataItem> data) { this.data = data; data.addOnListChangedCallback(new ObservableListCallback()); } @Override public BindingV...

Android Data Binding : Tricks and Magic

Image
You can do a lot of awesome things while using the Android Data Binding library. Some will save you a lots of time and some will seem like magic. You can see the full source code for this tutorial here . Custom XML attributes You can create custom xml attributes and add them to existing UI elements. For example if you ever had to use a custom font files in your application you would always have to set the type face programmatically as the TextView or its sub classes did not have an xml attribute to set the custom type face file from xml. With data binding you can implement your own attributes quick and easy. First lets define our binding adapter.  public class AttributeBindings { @BindingAdapter({"bind:typeface"}) public static void setTypeFace(TextView view, TypeFaceType tft) { Log.i("AttributeBindings", "setting typeface:"+tft); Typeface typeface = null; switch (tft) { case NORMAL: typefa...

Android Data Binding : How to Integrate Into Existing App

Image
Android Data Binding Library has been production ready for almost a year and you may be wondering if you can start using this great library in an existing project without introducing more bugs and without having to rewrite a lot of exiting code in your project. Yes you can, and its very easy to start! And why wouldn't you? Why wait to start a new project in few months or years and miss out on all the benefits of this library?! As the library offers significant time savings to developers and enforces good coding practices and as a result making your code cleaner and more maintainable. You can pull the the code for this tutorial here . It is easy to begin. If your project is minimum API level 7 or higher and is using Android Plugin for Gradle 1.5.0-alpha1 or higher then you can simply enable the Data Binding library by adding the following to the app module's build.gradle file android { .... dataBinding { enabled = true } } And that's it! Now you ...