December 2017 : This tutorial has not been updated for a while now and there could be breaking changes. I suggest that you instead reference the official documentation at https://cloud.google.com/endpoints/docs/frameworks/java/about-cloud-endpoints-frameworks

Welcome to Part 3 of the Google Cloud Endpoints Tutorial.

The full series:

Part 1 : We looked at writing a Google Cloud Endpoints class manually by using the various annotations and Exception classes that are available. We create a Quotes API that provided a JSON + REST based interface to manage Quotes (add, modify, delete and retrieve quotes).

Part 2 : We generated the Google Cloud Endpoints class from a JDO Annotated Entity class by using the Code Generation tools provided in the library.

Part 3 : Generated the Cloud Endpoints Client Library for Android and wrote an Android application that invokes the Endpoints API.

Part 4: We wrote a JavaScript client for our Endpoints API.

Part 5: Securing our API

Part 6: Calling a Secured API from a JavaScript client.

Part 7 : Calling a Secured API from an Android client.

IMPORTANT

This series covers Google Endpoints with Eclipse.

If you are looking for using Google Cloud Endpoints with Android Studio, I recommend my series on Gradle, especially the following parts:

Part 8 : Gradle + App Engine + Cloud Endpoints + Android Studio

Part 9 : Gradle + App Engine + Cloud Endpoints (Persistence) + Android Studio

Part 10 : Consuming Endpoints in your Android application

I have also published a list of Cloud Endpoints Tips:

In this episode

We have looked at generating the API implementation so far. You can pick and choose, whether you want to write it by hand or use the generated classes and tweak them to your liking. Whichever way you go, what we have now with us is an API backend that is hosted on the Google Cloud (App Engine) and we need to start consuming it via client applications.

In this part of the series, we are going to look at writing an Android client that consumes the Quotes API that we have ready and hosted. The tutorial will look at writing the application from scratch and demonstrating the List Quotes and Add New Quote function. Once you see that work, you can extend the Android application a bit further by incorporating the Edit Quote and Delete Quote as needed.

What do you need ?

Basic understanding of Android Application Development. Specifically, we will be looking at writing a few Activity classes, starting one Activity from another (via the Intent), using the Android AsyncTask to asynchronously invoke our API backend from the Android client. We shall be using Android stuff like ListActivity, Alert, Toast, Layouts, etc. If you are looking at brushing up on your Android fundamentals, look no further than this.

You have a working development environment for Google App Engine. This includes the Google Eclipse plugin.

You have a working development environment for Android. I have used Eclipse with the ADT Plug-in.

My Development Environment

This remains the same, no changes at all. My development environment is given below:

Eclipse Juno

Google Eclipse plugin with App Engine SDK 1.8.8

Android ADT Plugin with latest Android SDK installed.

Mac + Windows machine (I kept switching from one to another, to keep everyone happy ;-))

Attention-> Cloud Endpoints became GA (General Availability) in Release 1.8.7 of the App Engine SDK. The latest release as of App Engine at the time of writing is 1.8.9.

Revisiting the Quotes API

Let us recap quickly on what we have done so far. We have written a Quotes API hosted on Google App Engine that allows us to perform CRUD operations via a HTTP REST API. A Quote record contains a couple of attributes, the author and the famous quote that the author gave.

If you look at the API Methods, we had the following methods exposed:

Additionally, we have the application live and available on App Engine. And we have some records added to it, so that in case we do a listQuote, a record or two is available.

In case you are planning to follow the rest of the article, it would help to have the Quotes API ready and available under your App Engine application id.

Generate Google Cloud Endpoints library

Google Cloud Endpoints provides a way for us to generate the client side libraries. This can be done via the command line but we will be using the Eclipse plugin to keep things the way it has been so far.

Assuming that you already have your Eclipse Project for Quotes API Project loaded in Eclipse, simply right click on the Project, go to Google and then Generate Cloud Endpoint Client Library as shown below:

This will start generating Java classes that constitute the Client Library. It takes a while as shown by the dialog below:

Once done, you can take a look at the various folders that have been generated for you. The folders include the sources that act as a stub for your Quotes API and also a set of dependent JAR files.

For the Quotes API project that I have, the Client library folders are shown below:

At the same level as your src folder, you will find the endpoint-libs folder in which the sources and JARs are present.

The main points to take away is that:

You will need to take the classes that are generated in the quoteendpoint-v1-generated-source folder. These classes are client classes that act as a stub and which you can use in your Android application to invoke the CRUD operations in your hosted API.

folder. These classes are client classes that act as a stub and which you can use in your Android application to invoke the CRUD operations in your hosted API. More importantly, thats not all. You will need a bunch of dependent JAR files that are present in the dependencies folder and which you will need to carry along and link to in your Android project for everything to compile and eventually work.

We shall see that in a while.

Android Application Development

Before we dive into development of the Android client application, let us see it in action to better understand what we shall be building here.

When you launch the application, the first screen (Activity) is shown below:

The UI is simple and please do forgive me for my design skills :-) It has 3 buttons:

List Quotes : When clicked, it will start a new Activity that will Retrieve the current list of Quotes from the live App Engine application. A sample screen is shown below:

The List Activity is a simple ListActivity in Android. We use an Async Task to make the call via the Client library to get the Quotes and display them.

Add Quote : This Activity presents a simple form to the user to provide the Author name and the quote (message) as shown below:

When you click on Add, we will make a call to the Client library, which in turn will invoke the POST method to insertQuote in the live App. On successful addition, a message is shown to the user and when you go back to the List Quotes Activity, you see the newly added quote too, as given below:

Side Note: This is my only chance of being listed next to 2 great individuals. I stand no other chance. :-)

The 3rd button (About App) simply shows a simple Alert box and displays the name and the version number.

Let’s get started with the Android Application Development now. All the steps now will happen inside the Android Development Environment. I am using the ADT plugin inside of Eclipse. If you are using Android Studio, steps should be more or less familiar.

Generate Skeleton App

The first step is to create a new Project. Simply go to File -> New -> Android Application Project

Click on Next. In the screen below, we provide the name our App (FamousQuotesAndroid) along with package name. I have API 18 but you could have some other one too.

Click on Next. Deselect the Create custom launcher icon. Let the other values be as is and click on Next.

Go with the default on this screen too as shown below and click on Next.

The final screen is shown below. Simply click on Finish.

This will generate the Android Project. Ensure that it all compiles fine and verify that you are able to launch a AVD and run the basic application.

Add Google Client Library Classes and Dependencies (JARs)

The next step that we need to do is to add all the Cloud Endpoint classes and the Dependent JARs that were generated in the Quotes API Project.

You will need to add the JAR files shown below to the libs folder of your Android project. These JARs will be available in the dependencies folder of your Cloud Endpoint generated folder that we saw earlier.

The JAR files that you need to add are shown below:

The next thing to do is to add the Cloud Endpoint Java Source files that were generated in the quoteendpoint-v1-generated-source folder. Shown below is my Android Project Source structure:

As pointed out above, we have simply put the Cloud Endpoints generated Java files in the com.mindstorm package.

Similarly, the folder that you see below that i.e. Android Activities code is all the Android code that we shall see in a moment. It contains the Activity classes that compromise our Android application.

Understand Google Client Code and calling mechanism

It is important to understand to some extent what the Google Cloud Endpoints client classes look like.

The main class that you will deal with is the Quoteendpoint.java file. This is your starting point.

It contains the DEFAULT_ROOT_URL and the DEFAULT_SERVICE_PATH that you should modify if necessary so that the application points to your App Engine API which is hosted live at your application id.

It contains an inner class named Builder that you need to construct and get an instance of. The Builder constructor takes 3 parameters : Instance of the HTTP Connection Transport, an instance of GSONFactory for helping out in Java-JSON translations and an initializer.

Once the instance of a Builder is created, you will find that you can invoke all the API methods like listQuote, inserQuote, remoteQuote, getQuote and updateQuote, which you can then execute(). We shall see this in a while.

Android Activity Classes

Now let us go through the Android code. You do need to know a bit of basic Android Development over here, so most of the things should be straightforward. I have kept them deliberately simply and at a high level, you need to know the following things in Android:

Writing a basic Activity class and adding the entries in the AndroidManifest.xml file.

Invoking i.e. starting one Activity from the other. Basic Intent is used here.

Writing Event Handlers for button clicks. Knowledge of Linear Layout.

ListActivity

AsyncTask and why it is needed.

Android Main Activity class

This is the first screen that is shown in the Android application. There are 3 event handlers i.e. OnClick Listeners for the 3 buttons i.e. List Quotes, Add Quote and About App.

The List Quotes and Add Quote button click handlers simply start the respective Activities i.e. AddQuoteActivity and QuotesListActivity, that we shall see next.

Add Quote Activity

The code is given below but let us look at the main points:

The user enters the values for Author Name and Message and clicks on Add button.

button. The Add button click handler does some check for values and then invokes an Async Task: AddQuoteAsyncTask and passes the Strings i.e. Author Name and Message to it.

Pay attention to the AddQuoteAsyncTask class and the doInBackground method. Over here we construct the Quoteendpoint.Builder, create the Quote object and execute the insertQuote object. As simple as that.

Quoteendpoint.Builder builder = new Quoteendpoint.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), null); Quoteendpoint service = builder.build();

Quote quote = new Quote();

quote.setAuthor(params[0]);

quote.setMessage(params[1]);

response = service.insertQuote(quote).execute();

In the postExecute method of the Async Task, we simply clear up the fields.

Quotes List Activity

This code should be straight forward now.

In the onCreate we invoke the QuotesListAsyncTask.

The QuotesListAsyncTask will create the builder, invoke the listQuote method and collect the responses into a collection.

Finally in the postExecute method, we add the data to the List Adapter and boom, it displays the stuff in the ListView Control.

[gist]8452744[/gist]

This post talks about the list Quotes and Add Quote methods and has demonstrated that in the Android application. I hope that it is demonstrative of the fact that the update Quote, delete Quote and get Quote can also be executed accordingly and you can try it out.

Response Times

One of the important points to consider while using Google Cloud Endpoints is that your API is hosted on the App Engine platform. It is known that your application instance is not always running when for you. If it is idle for a while, your Application instance is removed and then on the next request, the instance is started up. The starting up (cold start) usually takes a while and anyone who has done work with App Engine is aware about this.

For e.g. look at the App Engine console log for the incoming requests below. I have highlighted in red, the abnormally high request processing time for particular API calls.

This is not to alarm you but it is something that you should be aware of. Definitely an API request that takes 15+ seconds to complete is not what you want. But at the same time, if the instance is alive, you do see a fast response time.

Please note that Google App Engine addresses the issue of keeping the instance alive via Warmup requests. Please read up on that.

Full Project Download

You can download both the Projects from GitHub.

API Project (This is the Server side API for Quotes)

Famous Quotes Android Project (The Android Source Project)

Hope you liked this episode of Google Cloud Endpoints in which we generated the Client Libraries for Android and also consumed it from an Android application.

Stay tuned for more episodes. Till the next one…