Android – How to consume an Azure Mobile Services?

Publishing core data through web service is always a work-intensive progress because we have to build up a web server, define service interface, make data access layer and implement user management. It has never been easy and always requires advanced knowledge. The resources of developers have to be distributed not only for client but also for server. Therefore the cost gets more. Moreover because of strong growth in market of smartphone and table running on different operating systems, the developers are put into a challenge to make a universal web service which can be easily consumed in all platforms. In my previous posts, such as How to call ASP.Net Web API service from Android? or Android – Media player and ASP.NET Web Api, we are able to build up a universal REST web service which can be consumed in all platforms supporting HTTP protocols.

However to build up such web service, we have to learn how ASP.NET Web Api works and so on. It would be nice if the web service can be built easily and we only have to focus in our client. Azure Mobile Services is a good candidate for the solution. Azure Mobile Services is a part of Microsoft Azure cloud service and is designed to make it easy to create highly-functional mobile apps with backend capabilities. For more details how it works, you can read at this Microsoft site

Mobile Services: http://msdn.microsoft.com/en-us/library/azure/jj554228.aspx

In this post, I’ll show you how to create a Mobile Service at Azure portal and consume it with an Android client.

1. Prerequisites

Please read this carefully, before continuing : You’ll need a Microsoft Azure account, if you don’t have any, you can apply for a trial version in 30 days (requires credit card, not for charging but for identifying). If you don’t get an account, then just read the post and understand the code. The code won’t run until you give it the correct URL and API Key, I can’t publish my Azure Mobile Service because my subscription is Pay-As-You-Go. I’ll be charged till my last cent if I publish my one as public service :). So, get an Azure account, follow the steps below and the sample code will run.
– Don’t try to connect to any service/database/SQL server discussed in this post because I prepared them only for demo and already deleted them when this post is published. Follow the steps and create your own service. Again, all of service/database/server shown in this post were already deleted, don’t try to access them.
– In source code, I’ll use AndroidAnnotations and Maven for injecting and referencing components. If you have no idea what they are, then read this post first Android – Introduction to AndroidAnnotations, Maven in Intellij IDEA

2. Azure Mobile Services

2.1 Create web service

– In this part, we’ll create a friendly mobile web service without having to enter any code row. Go to Azure portal https://manage.windowsazure.com and log in with your account.
– On the left menu, browse to Mobile Services and click New on the bottom menu

New Azure Mobile Services

– On the pop up menu, be sure that Mobile Services selected and click on Create

Create new Azure Mobile Service

– On the pop up window, enter URL of your mobile service and select Region. Region is very important, be sure that it should be as near as possible where your most customers are. It’ll affect the performance of your apps because of loading time. If most of your customers are in Asia and you choose West US as region, the messages have to ‘run’ through 2 continents and ‘swim’ over an ocean to reach your customers and you can imagine how slow it is. ;). So, be careful, the region can’t be changed after the service is created.

Create Azure Mobile Service Step 1

– On the next step, you have to enter the information of your database as well as your SQL server. Again, be careful with Region, if your Mobile Services locates in West US then the database should be there too. Keep your SQL server username and password carefully, you’ll need them for managing SQL server outside of Azure portal.

Create Azure Mobile Service Step 2

– Click to finish and the Mobile Service is ready after seconds. Click on URL to check if everything is in order.

Mobile Services ready

2.2 Database

– The Mobile Service was successfully. However there is still no defined contract/data for the service. On the left menu of Azure portal, select Mobile Services –> Select the new create service –> Data –> Add a table

Add new table

– Give a name for table and permission

Table name and permission

– After the table is created, you can browse available data by clicking on it

Table browse data

– In this demo, I’ll make a simple ‘To Do’ app as previous post Android – Sqlite database with ContentProvider and LoaderManage. So the table requires only 2 columns Id and Text, to design our table, go to Columns section and add new column Text

Add new column

New column Text

– If we want to edit data directly or execute SQL query, we have to configure the firewall so that we can access database from our IPs. On the left menu, select SQL databases –> Select Servers –> Click on server we want to connect –> Configure –> Add to the allowed IP addresses

Configure Server

– After adding your current IP to firewall exceptions, you can access SQL server by going to Dashboard –> On quick glance section, go to Manage URL

Manage URL

– Or we can also access server directly by SQL Managment Studio

Access with SQL Management Studio

3. Android client

– Our mobile service runs now and we can consume it. Microsoft Azure already prepared some starter code to get us familiar with Mobile Services. We can get this starter code pack for all platforms at Dashboard section of the Mobile Services

Starter code

– For Android client, we need Mobile Services SDK for Android

https://go.microsoft.com/fwLink/?LinkID=280126&clcid=0x409

– Download and add reference to it
– Ask Android for Internet permission so that your app can call yourMobile Service

<uses-permission android:name="android.permission.INTERNET" />

Important : I exclude the info of my Azure Mobile Service from code. You have to use your own by renaming class ConstantsSample to Constants and change URL and APIKey to correct value. The values of URL and APIKey can be got in starter code section

URL and APIKey

– Create a repository for our contract class ToDoItem. The Mobile Services SDK works asynchronously with a callback function notifying when an action is finished and it won’t block the UI when network operations run.

@EBean
public class ToDoItemRepository {
    private MobileServiceClient mobileServiceClient = null;

    @RootContext
    Context context;

    @AfterInject
    void afterInject()
    {
        try {
            mobileServiceClient = new MobileServiceClient(Constants.URL, Constants.APIKey,context );
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void loadAll(TableQueryCallback<ToDoItem> callback)
    {
        mobileServiceClient.getTable(ToDoItem.class).execute(callback);
    }

    public  void insert(ToDoItem toDoItem, TableOperationCallback<ToDoItem> callback)
    {
        mobileServiceClient.getTable(ToDoItem.class).insert(toDoItem,callback);
    }

    public  void update(ToDoItem toDoItem, TableOperationCallback<ToDoItem> callback)
    {
        mobileServiceClient.getTable(ToDoItem.class).update(toDoItem,callback);
    }

    public void delete(ToDoItem toDoItem, TableDeleteCallback callback) {

        mobileServiceClient.getTable(ToDoItem.class).delete(toDoItem,callback);
    }
}

Mobile Services SDK for Android uses GSon for serializing/deserializing object, remember to make reference to GSon in your pom.xml file

<dependencies>
 <dependency>
 <groupId>org.androidannotations</groupId>
 <artifactId>androidannotations</artifactId>
 <version>3.0.1</version>
 <scope>provided</scope>
 </dependency>
 <dependency>
 <groupId>org.androidannotations</groupId>
 <artifactId>androidannotations-api</artifactId>
 <version>3.0.1</version>
 </dependency>

 <dependency>
 <groupId>com.google.code.gson</groupId>
 <artifactId>gson</artifactId>
 <version>2.2.4</version>
 </dependency>

</dependencies>

– With annotation of GSon, we can specify which property should be mapped to which column.

public class ToDoItem implements Serializable {
    private String Id;

    @com.google.gson.annotations.SerializedName("text")
    private String Text;

    public String getId() {
        return Id;
    }

    public void setId(String id) {
        Id = id;
    }

    public String getText() {
        return Text;
    }

    public void setText(String text) {
        this.Text = text;
    }
}

– Then we can call Mobile Service easily through repository, such as filling out the adapter for ListView

@EBean
public class ToDoItemAdapter extends BaseAdapter {

    @RootContext
    Context context;

    @Bean
    ToDoItemRepository toDoItemRepository;

    List<ToDoItem> toDoItems = new ArrayList<ToDoItem>();

    @AfterInject
    void afterInjects() {
        loadData();
    }

    public void loadData() {
        toDoItemRepository.loadAll(new TableQueryCallback<ToDoItem>() {
            @Override
            public void onCompleted(List<ToDoItem> result, int i, Exception e, ServiceFilterResponse serviceFilterResponse) {
                toDoItems = result;
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getCount() {
        return toDoItems.size();
    }

    @Override
    public ToDoItem getItem(int position) {
        return toDoItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;// toDoItems.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ToDoItemView toDoItemView;
        if (convertView == null) {
            toDoItemView = ToDoItemView_.build(context);
        } else {
            toDoItemView = (ToDoItemView) convertView;
        }

        toDoItemView.bind(getItem(position));

        return toDoItemView;
    }
}

4. Conclusion

The Azure Mobile Service is easy to create, configure and consume. It can be easily scaled and adjusted on demand. With the help of Mobile Services SDK, we can easily consume Mobile Service in many popular platforms.

The sample source code can be checked out at https://bitbucket.org/hintdesk/android-how-to-consume-an-azure-mobile-service. Remember to use sample code with information of your Azure account, without Azure account, you can’t make it run.

5. Updates

21.06.2014

Another useful article for consuming Mobile Services within Android
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-how-to-use-client-library/

Leave a Reply

Your email address will not be published. Required fields are marked *