Davinder Singh is a Polymath. He loves reading, learning and writing technical cookbooks about new technologies.
What You Will Learn
- You will learn about fetching and parsing REST responses.
- How to load data from APIs that supports paging.
- Knowledge about different types of data sources that are provided in the Android Paging Library.
- How to use Giphy® API to query and download graphics integrated images.
- How to implement an infinite recyclerview with beautiful native animations.
Following is the list of things, I am assuming you already know irrespective of your level of expertise.
- How to create and setup new project in Android Studio a.k.a IntelliJ Idea.
- Basic familiarity with Kotlin Programming Language.
- Creating new packages, files and layouts in the Android Studio.
- Already know, how to implement recycler list view (Adapter, Item layout etc.).
- Have stable Internet connection.
What We Will Make
We will make a simple application implementing Android Paging Library component. Application will have an infinite recycler list view displaying search results from Giphy® through developer API.
What is Pagination
Pagination is an important concept in REST APIs. It is a technique by which search results are divided into smaller chunks called pages. Every page is thus a partition of larger result.
Advantage of this technique is that it divides the amount of data that client needs to process in a single go. And because of display area only certain number of results can be displayed on-screen; We can substantially reduce the memory footprint and network requirement of an application.
However, because of pagination instead of sending whole data at once, server sends data in chunks which create issue of synchronization between client and server. To tackle this, first result of call to API contains extra information for synchronization purposes. Every pagination API contains following mandatory fields:
- Total number of search results
- Number of search in current page
- Total number of pages
- Current page number
URLs can be provided with an [optional] argument page-number which gives client access to random page from set of pages (just like array indices).
Paging imparts additional overhead on servers. Because servers are powerful and implement technologies like caching and parallel processing; It becomes a win-win situation for both server and client.
Step 1: Setting Up Developers Account on Giphy®
First thing first let set up a developer's account at Giphy®. Giphy is a search engine platform for searching and sharing graphics integrated images(GIF) or moving picture. Go to Giphy.com and create a new login account if you don't already have one.
Developer's account is something that gives you access to all the application program interfaces that certain site provides to access their services. Some are paid while some are freely available with or without constraints. We will now create a developer's account on Giphy® to get access to services. Visit giphy® developer site and click button that says Get Started.
Click on Create an App. I am assuming that you already have made an account on Giphy®.
Give a name to your application. A description and finally check I only want to use Giphy® API. And then click Create New App. And we are done!
Next step copy the API key and save it for later.
Working With REST APIs
Before moving forward, let's have taste of Giphy's API. In this little demonstration, we will query giphy for all GIFs containing or tagged with word hello world.
Whole process consists of forming correct URL and then sending a get request to it. All APIs have following basic structure [BASE URL]\[END POINT]. Base URL of giphy API is https://api.giphy.com/v1/. If you follow the link then you will get a text response from Giphy similar to one given below
The response indicates 404 HTTP error also known as Not Found. Notation used to write response is called JSON which is acronym for JavaScirpt Object Notation. This is what all those applications that use REST API behind the curtain see. They parse specific fields out of these responses to respond to user. Let's do another one; this time with all the required arguments before moving forward to coding android application. Click on following link with all the X's replaced by API Key https://api.giphy.com/v1/gifs/search?q=hello&limit=5&api_key=XXXXXXXXXXXXX
Response from Giphy® Search API
You can know about this and many other end points from Giphy®'s documentation by visiting here.
Step 2: Android Application
Launch Android Studio and create a new android project with AndroidX articles. Also set Kotlin as main language. Also, add network access permissions in manifest of application.
Step 3: Dependencies
Our application can be divided into three separate parts which are
- Network Handling: This portion handles network aspect of application. Objectives of this portion are to manage network resources, caching results and then providing responses to data processing section.
- Data Processing: This is where raw responses are kept. Here we need to parse JSON responses from Giphy into kotlin objects. These objects store data corresponding to fields in JSON response.
- UI Handling: This is final portion. Here we load image data into ImageView and finally display them on screen in recycler list view.
Luckily, android has libraries already developed by someone which can handle everything for us all we need to do is to include them. To include them, add following dependencies in your application's gradle app module.
Step 4: Setup Project Tree
Before moving forward to coding, create following packages in the main package of application.
- For activities: activity
- For network handling code: network
- To store paging and view model related code: viewmodel
Finally, for user interface, create ui package.
Step 4: UI Layout
First we will create layout for application. Application consists of a recycler list view, edit text view for query input, a text view to display total results and finally a button to search for query.
Now, add two new layout resource files named small_item_layout and large_item_layout. And add a CardView in both of them with having width 150dp and height 250dp in large_item_layout while 210dp in small_item_layout. Lastly add SimpleDraweeView in both with match_parent in both width and height.
Step 5: Network Handler
Network handling module contains code that talk directly with Giphy® API; It parses the response and gives back kotlin class object containing fields from response. Network handler also handle errors that occur during network I/O. Add following files in network package:
- ApiConstants.kt: Contains all constants related to Giphy® API, for example API Key, base URL and search URL.
- EndPointGenerator.kt: This file consists of methods that return formatted string URLs based on request that we want to send. This saves us time and also reduces URL errors that occur during writing large URLs.
- NetworkHandler.kt: This file contains a static class which consists of methods providing abstraction over volley's network layer.
As said earlier, We are using Volley. Before moving forward let's first understand basics of Volley network library. Volley consists of two main components
- Request Queue: Global request queue is a queue of request that Volley executes in first-in-first-out fashion. Every request has associated listeners: A failure listener and A response listener. Type of response depends upon the type of request.
- Request: Volley supports different types of requests suitable for different scenarios. String request (which we will use) is for getting raw string response, JsonArrayRequest is for requesting array of objects in JSON and so on.
Response provided by volley in success callback is then given to GSon library which parses JSON response(basically a readable string) into Koltin object.
That was very brief explanation of Volley. You can learn more about it in here.
One final step in network left to do is to add JSON parsing information for GSON. For this, we need to add schema(structural information) of JSON response that Giphy® sends. This can be done in two ways, either with the help of automated tools such as this or by writing it from the scratch. For the sake of this tutorial we will write it from the scratch.
Step 6: ViewModel and Paging
Pagination consists of two main components: A View-Model and Data Source. View-Model provides state and lifecycle support while Data source acts as provider of data. All GUIs (recycler list view in our case) observe view-model for data changes or availability of new data and then update themselves accordingly.
Datasource is middle man between view-model and actual data source(either SQLite database or network feed). Pagination provides three types of data sources depending on useful in different scenarios:
- PagedKeyedDataSource: This data source is best suited for situations where response from API contains links for loading adjacent pages
- ItemKeyedDataSource: This data source comes in handy when data is already sorted and each item in data has unique id. To load items from 0 to N-1 you have to give id of 0th item and size up to which you want to load the list. And then to load next set of items i.e. from (N-1)+1 till N+K (say), id of Nth item and size K.
- PositionalDataSource: Positional data source is probably the most used and simplest of all data sources. It is used when result of API consist of number of results per page and number of pages such that you can randomly ask for any portion of result just by providing the right index.
Add following new files in viewmodel package: SearchViewModel.kt, GiphyDataSource.kt and DataSourceFactory.kt
Step 7: Finalising
Finally, let's complete application by adding last few snippets of code. Add two new files in ui package: InfiniteListAdapter.kt and RecyclerViewDecoration.kt for recycler list view and following code in MainActivity.kt to bind them all.
Well, that was all folks. Of course this was just a brief tutorial of what's possible with android pagination library. It supports much more and can be used in variety of ways and in different scenarios: Network, SQLite etc. You can learn more about it here.
Finally, I hope that I helped you in learning something new. Do feel free to ask question I sure will help you out or to give suggestions. Have a nice day!
This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.
© 2020 Dav Vendator
Dav Vendator (author) from Amritsar on March 29, 2020:
Thank you for your kind appreciations sir. I aim only to do that!
Halemane Muralikrishna from South India on March 29, 2020:
Thank you, Mr Davinder Singh, for sharing valuable android software coding. It was new learning experience for me here.
Sumit Goswami from Kolkata on March 29, 2020:
This is an incredible article with lot of information about Android Jetpack Paging Library. Also your photographs contain useful information about this technology.
Dav Vendator (author) from Amritsar on March 27, 2020:
Thankyou very much kind sir for the complement. I hope that article is easy to follow as much as it is elaborated!
Umesh Chandra Bhatt from Kharghar, Navi Mumbai, India on March 27, 2020:
Very elaborate and highly technical write up. Good article. Useful for Android professionals.