Over a million developers have joined DZone.

Consuming Azure Mobile Services from Android: Part 4

DZone's Guide to

Consuming Azure Mobile Services from Android: Part 4

· Cloud Zone ·
Free Resource

Learn how to migrate and modernize stateless applications and run them in a Kubernetes cluster.

 Next Steps

  1. The next post will cover:
    • Creating a new Android Application
    • How to name your application and modules
      • Application Name
      • Project Name
      • Package Name
    • Creating a simple hello world application
    • How to add a listview control
    • Understanding and adding import statements
    • Adding java code to populate the listview control with strings
    • Download the httpclient library from the Apache Foundation
    • Adding the httpclient library to our Android project
    • Adding code to call into Azure Mobile Services
    • Adding permissions to allow our Android app to call into Azure Mobile Services
    • Adding all the java code needed to call into Azure Mobile Services

Part 1 of 4: Introduction to Consuming Azure Mobile Services from Android http://blogs.msdn.com/b/brunoterkaly/archive/2012/10/03/part-1-of-5-introduction-to-consuming-azure-mobile-services-from-android.aspx
Part 2 of 4: Introduction to Consuming Azure Mobile Services from Android http://blogs.msdn.com/b/brunoterkaly/archive/2012/10/03/part-2-of-5-introduction-to-consuming-azure-mobile-services-from-android.aspx
Part 3 of 4: Introduction to Consuming Azure Mobile Services from Android http://blogs.msdn.com/b/brunoterkaly/archive/2012/10/03/part-3-of-4-introduction-to-consuming-azure-mobile-services-from-android.aspx
Part 4 of 4: Introduction to Consuming Azure Mobile Services from Android http://blogs.msdn.com/b/brunoterkaly/archive/2012/10/03/part-4-of-4-introduction-to-consuming-azure-mobile-services-from-android.aspx
Download Android Source Code https://skydrive.live.com/embed?cid=98B7747CD2E738FB&resid=98B7747CD2E738FB%213151&authkey=AN1ukGyTBgIY76Q
No obligation free trial for Azure Mobile Services http://www.microsoft.com/click/services/Redirect2.ashx?CR_CC=200114759

You will need a trial account for Windows Azure
  1. Please sign up for it here:

Creating a new application (Android, of course)
  1. This assumes you've installed:
    • Eclipse
    • Android SDK and tooling

Naming your Android Project
  1. Here you will specify:
    • Application Name
    • Project Name
    • Package Name

Choosing default images, clip art, and text
  1. This is how you might brand your application
  2. We will just choose defaults

Choosing the default Blank Activity
  1. We will build everything from scratch, rather than have the tooling give us a master/detail interface.
  2. We will simply add one listview control

Choosing the default Activity Name
  1. Naming our activity.
  2. This will result in how some of the main user interface files and code are named

Viewing the default project that was created by the Eclipse wizard
  1. We will now start editing code and building the interface

Running the default Android Template
  1. Let's run application just to see the default Hello World interface
  2. We will add our own code shortly.

Viewing the running project
  1. This is just to verify that all the tooling is working.
  2. Frankly, the emulators are not entirely reliable.
  3. In many cases, I had to run my samples more than once to see a correct result.

Working with the ListView Control
  1. Adapters & ListView Controls
    • A ListView receives its data via an adapter.
    • The adapter also defines how each row is the ListView is displayed.
    • The adapter is assigned to the list via the setAdapter method on the ListView object.
    • Android provides several standard adapters; we will use ArrayAdapter
      • ArrayAdapter can handle data based on Arrays or java.util.List.

Opening a text editor and adding our ListView Control
  1. We will now add our ListView control
  2. It is a simple case of modifying this XML file

Implementing the ListView Control
  1. We simply need to paste in the following code.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent" >
        tools:context=".MainActivity" >

Modifying MainActivity.java - adding "import" statements

  1. I will present the whole source code module (MainActivity.java) shortly
  2. These import statements are needed for the listview
  3. More will be needed for the httpclient code that is needed to call into Azure Mobile Services

Adding code to onCreate()
  1. onCreate() is the startup method where we can add some code.
  2. We will populate the listview control with some simple strings.
    • In the next section we will call into Azure Mobile Services to get data
    • But first let's understand the listview control.
  3. We will first add some code to add items to the ListView control.
  4. Notice the following:
    • We get the id for the ListView control so we can talk to it (note 1)
    • Create a string array of what we will add to the listview (note 2)
    • Create a ArrayAdapter and associate the strings from the previous step. (note 3)
    • Associate the ArrayAdapter with the ListView control (note 4)

Viewing the application so far
  1. Our simple example is working so far.
  2. Follow these steps:
    • From the menu, choose Run/Debug As/Android Application

Download the httpclient library
  1. Follow these steps:
    • Link is in the upper lift.
    • It will be a zip file.
    • Extract httpclient-4.2.1.jar to a folder.
    • Navigate to the folder.

Copying the httpclient library to our project
  1. This is needed because we will be calling into Azure Mobile Services.
    • httpclient.jar contains the code that allows use to make http calls into our Azure Mobile Service

Editing the code to call into the Azure Mobile Service
  1. The array values will now be populated with values we get from the Azure Mobile Service.
  2. A few things to note:

Opening the AndroidManifest.xml file
  1. We need to allow internet connectivity for our application.
  2. This is done in the AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >
   <uses-permission android:name="android.permission.INTERNET"></uses-permission>
        android:targetSdkVersion="15" />
        android:theme="@style/AppTheme" >
            android:label="@string/title_activity_main" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

  1. Our application will fail without this line.
  2. It is required.

Adding code to MainActivity.java
  1. You will now modify MainActivity.java to call into Azure Mobile Services
  2. You will two things from the portal to write this code:
    • The URL for Azure Mobile Services
    • The Application Id for Azure Mobile Services
  3. There are many important statements to add
package com.example.androidandmobileservices;

import android.os.Bundle;
import android.app.Activity;

import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

// Add these import statements
import android.util.Log;     // for logging

import org.json.JSONArray;   // for JSONArray
import org.json.JSONObject;  // for JSONObject

import java.io.InputStream;         // for reading the response as bytes
import java.io.BufferedInputStream; // for reading the response as buffered bytes  
import java.io.BufferedReader;      // for reading bytes in a buffered manner
import java.io.InputStreamReader;   // for reading bytes into BufferedReader
import java.net.HttpURLConnection;  // for HttpURLConnection
import java.net.URL;                // for URL

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

        // Define needed constants: (1) url to our mobile service; 
        // (2) service app id (from Azure Mobile Service Website)
        final String mobileServiceUrl = 
        final String mobileServiceAppId = 
            // Start building the request object to get the data 
            URL url = new URL(mobileServiceUrl);

            // Build a request object to connect to Azure Mobile Services
            HttpURLConnection urlRequest = (HttpURLConnection) url.openConnection();

            // Reading data so the http verb is "GET"

            // Start building up the request header
            // (1) The data is JSON format 
            // (2) We need to pass the service app id (we get this from the Azure Portal)
            urlRequest.addRequestProperty("Content-Type", "application/json");
            urlRequest.addRequestProperty("ACCEPT", "application/json");
            urlRequest.addRequestProperty("X-ZUMO-APPLICATION", mobileServiceAppId);

            // We hold the json results
            JSONObject[] todos = null;

            // The listView control that will populate with data
            ListView listView = (ListView) findViewById(R.id.mylist);
                // Prepare some objects to receive the bytes of data
                // from the Azure Mobile Service
                InputStream in = new BufferedInputStream(
                BufferedReader bufferReader = new BufferedReader(
                        new InputStreamReader(in));

                // responseString will hold our JSON data
                StringBuilder responseString = new StringBuilder();
                String line;

                // Loop through the buffered input, reading JSON data
                while ((line = bufferReader.readLine()) != null) 

                // Convert responseString into a JSONArray
                JSONArray jsonArray = new JSONArray(responseString.toString());

                // Will hold an array of JSON objects
                todos = new JSONObject[jsonArray.length()];

                // values is very important. It is the string array that will
                // get assigned to our ListView control.
                String[] values = new String[jsonArray.length()];
                String s;

                // Loop through the objects. The ultimate goal is to have
                // an array of strings called "values"
                for (int i = 0; i < jsonArray.length(); i++) 
                    todos[i] = jsonArray.getJSONObject(i);
                    values[i] = todos[i].get("text").toString();

                // Create an array adapter using the string array called "values"
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_1, android.R.id.text1, values);
                // Assign adapter to ListView
            } catch (Exception ex) {
                Log.e("MainActivity Failure", "Error getting JSON from Server: "+ ex.getMessage());
            } finally {
          } catch (Exception ex) {
            Log.e("MainActivity Failure", "Error opening HTTP Connection: " + ex.getMessage());


    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;


  1. We are now finished and have learned the following lessons:
    • How to setup our Azure Mobile Services
    • How to add tables, insert data to a relational database
    • How to use http to issue GET and POST commands
    • How to use low-level tooling (Fiddler) to interact with Azure Mobile Services
    • How to create an Android application to read data from Azure Mobile Services.
  2. I bid you farewell. Thanks for reading.

You will need a trial account for Windows Azure
  1. Please sign up for it here:

I appreciate that you took the time to read this post. I look forward to your comments.

Join us in exploring application and infrastructure changes required for running scalable, observable, and portable apps on Kubernetes.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}