Thursday, October 30, 2014

How to build Android app with the Cloud Platform at the backend - Phase I

This tutorial describes how to develop a mobile application powered by Google Cloud Platform. The application includes an Android client and an App Engine backend. 
This tutorial will produce an app called mobile shopping Assistance.

You will write custom code to wire the basic Android app client to the App Engine cloud backend, using Google cloud endpoints, so it can determine user location, locate nearby stores, and allow the user to obtain relevant offers and recommendations.
The following figure shows the main components of such application. Notice that the example in this tutorial only applies to the Android platform.

Target Audience

This tutorial is directed to any developer interested in learning how to build services in the cloud and use them from mobile applications which give to the customers a more engaging environment and better experience.
You need to know how to program in Java and use Eclipse. Also, you should be familiar with building Android mobile apps. A basic knowledge of App Engine technology is not required but is a plus.

Tools and Packages Required

Make sure you have installed the following tools and packages for the tutorial:


  • Eclipse version 3.8 or higher. Install the tool from here.

App Engine

  • Google Plugin for Eclipse. You can download the necessary plugin here. Note that if you install the GPE includes you do not have to install the App Engine SDK s eparately.


  • Android Development Tools (ADT). Install the Android tools (plugin) for the Eclipse IDE by following the steps described here: Installing the Eclipse Plugin.
    From within Eclipse, open the Android SDK manager to install the latest SDK platform tools. It is recommended that you install the latest Google API. The example shown in this tutorial were verified using API level 17.

Phase 1: Setup Mobile Assistant Application

In this phase you’ll learn how to set the development environment to build the mobile application. You’ll also learn how to allow the client to communicate with the mobile backend.
The application will contain the following projects:
  • MobileAssistant. This is the Android client that provides the UI. I n the background, the client interacts with the App Engine to gather stored information requested by the customer.
  • MobileAssistant-AppEngine. This is the backend project which provides the service in the cloud.
By following the steps described in this section, you will create an Android project with a n App Engine backend. The Android client will be able to call the backend.
As you progress, the tutorial will show you how to test what you have built up to that point.

Download Sample Code

Download the code from the MobileAssistant-Tutorial folder in Mobile Shopping Assistant. The archive contains phase 1 and phase 2 snippets that you need for the tutorial. It also contains a basic project that you might use as a reference.

Setup Android Development Environment

If you already know how to setup an Android development environment and create an Android client application project, you can skip to Setup App Engine Backend Application Project after you c reate a client application project called MobileAssistant.
  1. After you have downloaded the SDK, follow the instructions described in: Setting Up an Existing IDE. Remember that the tutorial assumes that you have already installed Eclipse.
  2. To develop Android applications, you also need to download at least one Android platform and the latest SDK Platform-tools. Follow the steps described in:Adding Platforms and Packages.
  3. In the Eclipse toolbar menu, click Help.
  4. In the drop-down menu, click Install New Software. The Install wizard is displayed.
  5. In the Work with: box enter
    Google Update Site for Eclipse 4.2 -
    Notice that the version of the plugin depends on the version of your Eclipseinstallation.
  6. Read and accept the license agreement and click Finish.
  7. Click Next.

Create Android Client Application Project

This section shows you how to create a mobile client application project. The application provides the interface which allows the customer to interact with the backend, for example to obtain sales information.
  1. In Eclipse, click File then select New.
  2. Click Android Application Project.
  3. The New Android Application wizard window is displayed.
  4. In the Application Name box, enter the name of your application, for example MobileAssistant.
  5. In the Package Name box, enter the name of your application’s package, for
  6. In the Target SDK drop-down list box, select the API version you want to use. In the example this value is: API 17: Android 4.2.
  7. In the Compile With drop-down list box, select the same API version you used in the previous step.
  8. In the Theme drop-down list box, select a theme that is supported by the API version you chose in the previous steps. You can accept the default value.

Figure 1 Android Application wizard
  1. Click Next.
  2. In the next window that is displayed, accept the default values and click Next. The Configure Launcher Iconwizard window is displayed.
  3. Make the icon selections or accept the default values, click Next. The Create Activity wizard window is displayed.
  4. In the activity list box, select BlankActivity.
  5. Click Next. The New Blank Activity wizard window is displayed.
  6. If prompted, install the dependencies. Accept the default values and click Next.
  7. Click Finish.
    The MobileAssistant project is created. The project contains several generated classes that belong to package.

Setup App Engine Backend Application Project

This section shows you how to set up the project to create the mobile backend application which runs on Google Cloud Platform (App Engine). The application contains the data repository and the business logic to support the mobile client requests.
  1. In the Package Explorer, right-click on the project name MobileAssistant.
  2. In the drop-down menu, click Google.
  3. In the side menu click Generate App Engine Backend...
    In the displayed wizard, y ou can skip the steps for entering the Project Number and API key, unless you plan on using the generated sample code (described in the Creating App Engine Connected Android Project ).
  4. Click Create and let the operation finish. The MobileAssistant-AppEngine project is created along with anendpoint library in the client application. For more details about endpoints, see EndPoint Client Library Basics. The project contains several generated classes that belong to package.
So fa r you have created the environment for the development of the mobile assistant application, for both client and backend. In the next section you’ll start building the application and then test the communication between the mobile device and the App Engine cloud service.

Start Building the Application

In this section you will start building the application by creating a simple CheckIn entity class that allows the customer to check in a store, using her mobile device.
An entity class provides an “object-relational interface” between your application and the backend data repository.
After the customer checks in, the class insert s the store information in the backend datastore.
Now, let’s create the class in the MobileAssistant-Appengine backend application by following these steps :

Create an Entity Class

  1. In the Package Explorer, under the AppEngine project src folder, right-click the package, then select ->New->Class. The New Java Class wizard is displayed.
  2. In the Name: box enter CheckIn.
  3. Click Finish.
    For more information about the kind of class created, see the App Engine DataStore Overview.
  4. In the editor, replace the boiler plate code with the code for the class that you can obtain from the snippets archive downloaded earlier. Notice that the code shown provides a “ready to run” class. The most important things you must pay attention to are the 3 properties and the annotations.
  5. Save the class.

Generate a Cloud Endpoints Class and Library

  1. Create the class and related client library by following the steps described in: Entity Class Design Pattern. The following figure shows the entry for the client library in the MobileAssistant client project.
    Figure 2 CheckIn Endpoint Client Library
Open the class in the editor. Then, in the insertCheckIn method delete the following lines:
if (containsCheckIn(checkin)) {
throw new EntityExistsException("Object already exists");
This is because the CheckIn class is configured to use auto-generated key s. This is defined by the attribute@GeneratedValue(strategy = GenerationType.IDENTITY).
Using the endpoint design pattern and with minimal custom code, you have created the infrastructure that allows the communication between the client and the backend.
Before going forward, you’ll test the current minimal code and verify that the client and backend applications can communicate.

Modify the Client Application

In this section you’ll add some code to the MainActivity class to test if the client communicates with the backend. The code contains a CheckInTask class. At power-up this class sends a fictitious store ID to the backend endpoint to indicate that the customer has checked in.
Follow these steps to add the code:
  1. In the Package Explorer, in the MobileAssistant project, expand the file.
  2. In the editor, open the MainActivity class.
  3. Replace the boiler plate code with the code find in the file that you can obtain from the snippets archive downloaded earlier.
  4. Save the class.
This code sets the store ID to the arbitrary value StoreNo123. This ID is assigned to the CheckIn variable setPlaceIdthat will be stored in the App Engine datastore. You will see this value displayed in the Datastore viewer during testing described in the next section.

Test Client and Backend Communication

The goal of this test is to verify that the code written so far is working and that the infrastructure is in place so the client and backend can communicate. Specifically, you must verify that the fictitious store ID sent by the client is stored in the App Engine datastore.
The following snippet, from the Android class, shows the code that calls the backend:
Checkinendpoint.Builder builder = new Checkinendpoint.Builder(
AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);
Checkinendpoint endpoint =;
Note. This test runs on your local development server, so you first must start the backend and then the client application.
  1. In the Package Explorer, in the MobileAssistant project, expand the class.
  2. In the editor, open the CloudEndPointUtils and set LOCAL_ANDROID_RUN = true as shown next.
    This indicates that the MobileAssistant client application connects to the local d evelopment server.
  3. In the Package Explorer, right-click on the MobileAssistant-AppEngine project.
  4. Select Debug As ->Web Application.
    The application MobileAssistant-AppEngine starts on the local server.
  5. In the Package Explorer, right-click on MobileAssistant project.
  6. In the drop-down menu, select Debug As.
  7. In the side menu click Android Application.
    This starts the MobileAssistant client Android application simulation. The application will communicate with the backend MobileAssistant-Appengine.
    If you have not selected a device for the emulation, you ’ ll be asked to do so now. Follow the steps indicated by the wizard. The model 4.0”WVGA (480x800:hdpi) was selected for the example in this tutorial.
    If you get errors with 'R' being undefined and this is the first time you've tried to compile the project, it's likely that you've incorrectly installed the SDK.
    If you receive this error on subsequent builds, try deleting "" (a generated class) and see whether you can regenerate it successfully. If this step fails, some error exists in the files of the "res" (resources) directory. Look for Eclipse warnings particularly in the XML files.
    To complete the test, you must verify that the store ID is stored in the App Engine datastore by performing the following steps:
  8. In the browser of your development server, enter the following URL http://localhost:8888/_ah/admin. You will get a display similar to the following:
    Figure 3 Datastore viewer
  9. Click List Entities. This displays the CheckIn entity instance that contains the fictitious store ID. You should look for an entity with placeid = StoreNo123, as shown in the following figure. T his proves that the client communicates with the backend.
    Figure 4 CheckIn entity list
    With this, you have completed the preliminary steps in creating the mobile a pplication infrastructure.
    In the next steps, you ’ ll add logic to the backend that allows the customer to obtain information about places (stores) contained in the backend data repository.

Obtain Store Information

This section shows how to add more logic to the application to allow the customer to obtain information about stores contained in the backend repository. To achieve this goal, you must add a new entity class to theMobileAssistant-Appengine backend application called Place. In a real world application the information would be about places near to the customer’s location obtained in real time through GPS. The example uses simulated information contained in the App Engine datastore. Refer to the test section shown later to see how to populate the datastore.
  1. In the Package Explorer, under the MobileAssistant-AppEngine project in the src folder, right-click the package, then select ->New->Class.
    The New Java Class wizard is displayed.
  2. In the Name: box enter Place.
  3. Click Finish.
  4. In the editor, replace the boiler plate code with the code contained in the file that you can obtain from the snippets archive downloaded earlier.
  5. Save the class.
  6. Create the class and related client library by following the steps described in: Entity Class Design Pattern.
You have created the infrastructure that allows the client application to retrieve places information that is in the backend datastore.

Modify the Client Application

Let’s now modify the client application again. This will allow you to obtain information from the the backend and display it in your Android client application.
  1. In the Package Explorer, in the MobileAssistant project, expand the file.
  2. In the editor, open the MainActivity class.
  3. Replace the existing code with the version in the file that you can obtain from the snippets archive downloaded earlier.
In this new version of the code, t he global resultsList variable contains the information obtained from the backend.
The client application instantiates the ListOfPlacesAsyncRetriever class at the creation time and calls its execute method (in the onCreate method).
The class makes asynchronous Mobile Assistant API calls when the customer check into a place. In the example code, it retrieves places information from the backend.
You will see this information displayed in the Android client application.

Modify Activity_main.xml

  1. In the Package Explorer, in the MobileAssistant project, expand the res folder and then the layout folder.
  2. Open the Activity_main.xml file. A dd the line of code shown next (to modify the existing TextView). This assures that the information retrieved from the backend is displayed by the Android client. R efer to the next test section to learn more about the information to be retrieved.
This defines a single layout covering the whole screen (the width and height values are “match_parent”). Inside the layout there is a single “TextView” element. This text box is initialized with the string literal “@+id/results” which identifies the list of the stores.
The results identifier is used in the OnCreate routine as follows :
resultsList = (TextView) findViewById(;
This allows access to the widget so you can set new content (the list of stores). Notice, you can open theActivity_main.xml file using the Android XML (visual) editor and you can assign the value @+id/results to the Id property.

Test Display of Store Information

The purpose of the test is to retrieve the list of places from the backend. The test is performed on local development server. Refer to the steps performed in the case of the CheckIn entity class to enable local testing. Before you can proceed with testing, you must populate the backend repository with data, as shown next.

Create Upload Script

This is the script that actually uploads the simulated information into the backend datastore.
For information about the bulkloader.yaml and more, refer to the App Engine documentation in: Uploading and Downloading Data. Also, you can find the bulkloader.yaml file and the test data here MobileAssistant-Data.
  1. Create a new directory and make it your current directory.
  2. In your editor, create a script file and call it
  3. Copy and paste the following code into the file.
    #!/bin/sh upload_data
    --config_file bulkloader.yaml --url=http://localhost:8888/remote_api --filename $1 --kind=$2 -e
    The previous script accepts two arguments separated by a blank space:
    ./<data.csv> <class entity name>
    The first argument is the name of the csv file that contains the data you want to upload, The second is the name of the entity class to handle the data.
  4. Close and save the file. Notice that the script at this time is intended to be used on local server. It must be modified when the backend application is deployed to the cloud. For example, e-mail “” will be changed to an actual e-mail address of the App Engine administrator before deployment.

Places Simulated Data

The simulated data is contained in the file places.csv that you downloaded earlier from the MobileAssistant-Data directory in Mobile Shopping Assistant.
The file contains the following comma separated fields:
  • name: <place’s name>
  • placeId: <number that identifies the place>
  • location: <place’s latitude and longitude coordinates (two values separated by a comma) >
  • key: <unique key associated with the place>
  • address: <the place’s address >

Modify Web.xml

To upload data to the datastore, reference the “remote API servlet” and associate it with a URL. You’ll define these mappings in the Web.xml file of the MobileAssistant-Appengine application, as shown next. The web server uses this configuration to identify the servlet to handle a given request.
Note. Notice, you might need to restart Eclipse. if you skip th e Web.xml modification you will get Error 404 Not Found.
<display-name>Remote API Servlet</display-name>

Upload Places Simulated Data

To upload the test data to the data store, run the script that uploads the data from your script directory.
Before you upload your data, make sure to start MobileAssistant-AppEngine as a Web Application (in Debug mode) in Eclipse.
  1. ./ <places.csv> Place
  2. At the password request, just press enter.
To ensure that the data has been uploaded in the datastore, perform the same steps you followed in the case of theCheckin class. Refer to Test Client and Backend Communication section from step 3 forward.
In the browser of your development machine, open the App Engine administration dashboard at:http://localhost:8888/_ah/admin,
  1. Select Place in the drop-down list a shown in the next figure.
  2. Click List Entities. This displays the places information you uploaded.

Display Store Information

  1. In the Package Explorer, in debug mode, first start the MobileAssistant-AppEngine as a Web application then the MobileAssistant-AppEngine as an Android application, as you did when testing the CheckIn class.
  2. Unlock the emulator to display the places information, as shown next.
    Figure 5 Android Emulator Display Store Information

No comments:

Post a Comment