Consuming Azure Mobile Services from Android: Part 4
- 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
- Please sign up for it here:
- This assumes you've installed:
- Eclipse
- Android SDK and tooling
- Here you will specify:
- Application Name
- Project Name
- Package Name
- This is how you might brand your application
- We will just choose defaults
- We will build everything from scratch, rather than have the tooling give us a master/detail interface.
- We will simply add one listview control
- Naming our activity.
- This will result in how some of the main user interface files and code are named
- We will now start editing code and building the interface
- Let's run application just to see the default Hello World interface
- We will add our own code shortly.
- This is just to verify that all the tooling is working.
- Frankly, the emulators are not entirely reliable.
- In many cases, I had to run my samples more than once to see a correct result.
- 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.
- We will now add our ListView control
- It is a simple case of modifying this XML file
- We simply need to paste in the following code.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://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
![]()
- I will present the whole source code module (MainActivity.java) shortly
- These import statements are needed for the listview
- More will be needed for the httpclient code that is needed to call into Azure Mobile Services
- onCreate() is the startup method where we can add some code.
- 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.
- We will first add some code to add items to the ListView control.
- 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)
- Our simple example is working so far.
- Follow these steps:
- From the menu, choose Run/Debug As/Android Application
- 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.
- 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
- The array values will now be populated with values we get from the Azure Mobile Service.
- A few things to note:
- The URL that the Android client will call:
- public static final String kGetTodosUrl = https://brunotodoservice.azure-mobile.net/tables/TodoItem;
- Recall the brunotodoservice is something we defined when we created our Windows Azure Mobile Service.
- public static final String kGetTodosUrl = https://brunotodoservice.azure-mobile.net/tables/TodoItem;
- The URL that the Android client will call:
- We need to allow internet connectivity for our application.
- This is done in the AndroidManifest.xml file
<manifest xmlns:android="http://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>
- Our application will fail without this line.
- It is required.
- You will now modify MainActivity.java to call into Azure Mobile Services
- You will two things from the portal to write this code:
- The URL for Azure Mobile Services
- The Application Id for Azure Mobile Services
- 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 {
@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;
}
}
- 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.
- I bid you farewell. Thanks for reading.
- Please sign up for it here:
I appreciate that you took the time to read this post. I look forward to your comments.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





