Android networking is typically very involved if you try to implement bottom-to-top. So, we rely on third party libraries. But never understand what’s underneath it. In this example I have taken the very foundation of networking java.net package to build netwoking framework that is powered by JPost, a class communiction framework.
This is a Java / android library facilitating modular, asynchronous and controlled messaging between classes. The main features of this library are as listed below:
- In contrast to the existing pub-sub libraries, it hold the subscribers with weakreference. Thus it doesn’t create memory leaks.
- Single message can be sent to selected subscribes. This avoids the problem of event getting received at undesirable places. Thus minimising the chances of abnormal application behaviour.
- The subscriber addition can be controlled by using private channels. It minimises the chances of adding subscribes by mistake to receive undesirable messages.
- It is a tiny library < 55kb . Thus not affecting the application overall size.
- It facilitates synchronous as well as asynchronous message delivery and processing.
- It provides a mechanism to run code asynchronously.
What is that we will build?
We will build an android application that make network calls to get list of repositories of an user and list them in a ListView. The screenshot of the result is shown below.
If you have been following my tutorials, you would know that we follow a step oriented approach to build things up. One step at a time. Stick to your seat for half an hour, to go through a journey deep into coding.
Are you ready?
Let’s start building:
Create an Android Studio project and select “Empty Activity” template.
Now Get things to cook the code.
Import two libraries in the build.gradle of the app’s module:
- Gson is a very popular JSON parsing library. It helps convert an object into a json object and vice-versa.
- JPost is a class communication library as explained above.
Create a layout for the MainActivity: res/main/activity_main.xml
- It has a ListView to show the items in a vertical list.
Similarly create the list item view layout: res/layout/repo_list_item.xml
- It contains 4 row views to display 4 properties from the api response.
Create a class Applications that extends android.app.Application . We want to do an initialization of the networking framework, that we are building. So, we need to define it when the application starts.
Also put android:name=”.Application” (inside <application> Tag) in the AndroidManifest.xml so that the app knows, it has to execute this class when it runs.
- ApiHandler class we will be defining in a moment.
Create a data model class to be constructed from json response.
- “@SerializedName” : Is an annotation from gson library that maps the variable to the json key.
- “@Expose” : It is an annotation from gson library. It makes only the variable with expose to be available for parsing.
Create a class GitRepoMsg to be used as a message to pass the parsed json response on the channel that we will define subsequently.
- This class contains a list of GitRepo objects that is parsed from the api response using gson.
Create RepoListAdapter, a listview adapter to populate the listview.
- The adapter is passed a list of GitRepo objects which it used to populate the list item views.
- setGitRepoList method re-initializes the list and call to repopulate the list item views with new data.
Now the most fun part
Create a class ApiHandler to manage the api calls. Let’s see this class first and then will try to understand it.
- GIT_REPO_URL is a defines to facilitate the referencing to the api endpoint from any class.
- API_CHANNEL_ID is the int id, we want to attach to a private channel we are creating through JPost. JPost provides three kinds of channel. Default, Public and Private, Private channel is used to communicate with the subscribers in a controlled way. Only Creator can add subscribers on this channel and only subscribers of this channel can post messages over it. For more details click here JPost.
- We have init method to instantiate the ApiHandler class.
- The ApiHandler() constructor creates a private channel with channel id.
- doGitRepoGetApiCall method provides an interface to make api call. It sends a message over the api channel to make the api call and process it in a non UI thread.
- “@OnMessage” is from JPost. It binds a method to receive message on the channel.
- processGitRepoGet method creates HttpURLConnection by opening the connection and makes get request on the provided url. It gets the api response in an input stream. From the input stream it creates a StringBuffer to be used to parse the json.
- Through GsonBuilder we gets a gson object and use it’s fromJson method to get an array of parsed GitRepo objects. The array is converted into List using Arrays.asList method.
- The GitRepoMsg is instantiated and send on the DEFAULT GLOBAL channel of the JPost. Default global channel sends and receives messages for all the subscribes.
- See https://github.com/janishar/JPost for documnetation on JPost.
Define the MainActivity class
- MainActivity subscribes to JPost’s Default Channel using addSubscriber(object) method
- “@OnUiThread” : Annotation is provided by JPost to run the code on the Android UI thread.
- It receives the response message through the default global channel and updates the listview
You can appreciate the JPost for making such a networking architecture so simple and robust. This was a guideline example. The path to a complete system development is left as an exercise.