Part 4 of 4: Introduction to Consuming Azure Mobile Services from Android


Next Steps

001

  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 https://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 https://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 https://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 https://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 https://www.microsoft.com/click/services/Redirect2.ashx?CR_CC=200114759

You will need a trial account for Windows Azure

002

  1. Please sign up for it here:

Creating a new application (Android, of course)

003

  1. This assumes you've installed:
    • Eclipse
    • Android SDK and tooling

Naming your Android Project

004

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

Choosing default images, clip art, and text

005

  1. This is how you might brand your application
  2. We will just choose defaults

Choosing the default Blank Activity

006

  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

007

  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

008

  1. We will now start editing code and building the interface

Running the default Android Template

009

  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

010

  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

011

  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

012

  1. We will now add our ListView control
  2. It is a simple case of modifying this XML file

Implementing the ListView Control

013

  1. We simply need to paste in the following code.

activity_main.xml

  activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"     xmlns:tools="https://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent" >       <ListView         android:id="\@+id/mylist"         android:layout_width="match_parent"         android:layout_height="wrap_content"         tools:context=".MainActivity" >     </ListView>   </RelativeLayout>

Modifying MainActivity.java - adding "import" statements

014

  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()

015

  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

016

  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

017

  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

018

  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

019

  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

020

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

AndroidManifest.xml

  AndroidManifest.xml
1234567891011121314151617181920212223242526272829 <manifest xmlns:android="https://schemas.android.com/apk/res/android"    package="com.example.androidandmobileservices"    android:versionCode="1"    android:versionName="1.0" >    <uses-permission android:name="android.permission.INTERNET"></uses-permission>      <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="15" />     <application        android:icon="\@drawable/ic_launcher"        android:label="\@string/app_name"        android:theme="\@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="\@string/title_activity_main" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application> </manifest>

021

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

Adding code to MainActivity.java

022

  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

 MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 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 {     \@Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         // Define needed constants: (1) url to our mobile service;          // (2) service app id (from Azure Mobile Service Website)         final String mobileServiceUrl =                  "https://brunotodoservice.azure-mobile.net/tables/TodoItem";         final String mobileServiceAppId =                  "FIoFunrUPBDhaFmmEXFHJCZoFEZILW45";         try         {             // 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"             urlRequest.setRequestMethod("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);                          try                 {                 // Prepare some objects to receive the bytes of data                 // from the Azure Mobile Service                 InputStream in = new BufferedInputStream(                         urlRequest.getInputStream());                 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)                  {                     responseString.append(line);                 }                 // 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                 listView.setAdapter(adapter);                                } catch (Exception ex) {                 Log.e("MainActivity Failure", "Error getting JSON from Server: "+ ex.getMessage());             } finally {                 urlRequest.disconnect();             }           } catch (Exception ex) {             Log.e("MainActivity Failure", "Error opening HTTP Connection: " + ex.getMessage());        }              }     \@Override     public boolean onCreateOptionsMenu(Menu menu) {         getMenuInflater().inflate(R.menu.activity_main, menu);         return true;     } }

Conclusion

023

  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

024

  1. Please sign up for it here:

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