Free trial

Get started with data in Mobile Services

This topic shows you how to use Windows Azure Mobile Services to leverage data in an Android app. In this tutorial, you will download an app that stores data in memory, create a new mobile service, integrate the mobile service with the app, and then login to the Windows Azure Management Portal to view changes to data made when running the app.

Note

This tutorial is intended to help you better understand how Mobile Services enables you to use Windows Azure to store and retrieve data from an Android app. As such, this topic walks you through many of the steps that are completed for you in the Mobile Services quickstart. If this is your first experience with Mobile Services, consider first completing the tutorial Get started with Mobile Services.

This tutorial walks you through these basic steps:

  1. Download the Android app project
  2. Create the mobile service
  3. Add a data table for storage
  4. Update the app to use Mobile Services
  5. Test the app against Mobile Services

This tutorial requires the Mobile Services Android SDK; the Android SDK, which includes the Eclipse integrated development environment (IDE) and Android Developer Tools (ADT) plugin; and Android 4.2 or a later version.

Note

This tutorial provides instructions for installing both the Android SDK and the Mobile Services Android SDK. The downloaded GetStartedWithData project requires Android 4.2 or a later version. However, the Mobile Services SDK requires only Android 2.2 or a later version.

Download the projectDownload the GetStartedWithData project

This tutorial is built on the GetStartedWithData app, which is an Android app. The UI for this app is identical to the app generated by the Mobile Services Android quickstart, except that added items are stored locally in memory.

  1. Download the GetStartedWithData sample app and expand the files on your computer.

  2. In Eclipse, click File then Import, expand Android, click Existing Android Code into Workspace, and then click Next.

  3. Click Browse, browse to the location of the expanded project files, click OK, make sure that the TodoActivity project is checked, then click Finish.

    This imports the project files into the current workspace.

  4. In Package Explorer, expand GetStartedWithData, src, and .com.example.GetStartedWithData, then examine the ToDoActivity.java file.

    Notice that there are //TODO comments that specify the steps you must take to make this app work with your mobile service.

  5. From the Run menu, click Run As and then click 1 Android Application to start the project.

    Note

    You can run this project using an Android phone, or using the Android emulator. Running with an Android phone requires you to download a phone-specific USB driver.

    To run the project in the Android emulator, you must define a least one Android Virtual Device (AVD). Use the AVD Manager to create and manage these devices.

  6. In the app, type meaningful text, such as Complete the tutorial, and then click Add.

    Notice that the saved text is stored in an in-memory collection and displayed in the list below.

Create mobile serviceCreate a new mobile service in the Management Portal

Next, you will create a new mobile service to replace the in-memory list for data storage. Follow these steps to create a new mobile service.

  1. Log into the Windows Azure Management Portal.
  2. At the bottom of the navigation pane, click +NEW.

  3. Expand Compute and Mobile Service, then click Create.

    This displays the New Mobile Service dialog.

  4. In the Create a mobile service page, type a subdomain name for the new mobile service in the URL textbox and wait for name verification. Once name verification completes, click the right arrow button to go to the next page.

    This displays the Specify database settings page.

    Note

    As part of this tutorial, you create a new SQL Database instance and server. You can reuse this new database and administer it as you would any other SQL Database instance. If you already have a database in the same region as the new mobile service, you can instead chooseUse existing Databaseand then select that database. The use of a database in a different region is not recommended because of additional bandwidth costs and higher latencies.

  5. In Name, type the name of the new database, then type Login name, which is the administrator login name for the new SQL Database server, type and confirm the password, and click the check button to complete the process.

    Note

    When the password that you supply does not meet the minimum requirements or when there is a mismatch, a warning is displayed.
    We recommend that you make a note of the administrator login name and password that you specify; you will need this information to reuse the SQL Database instance or the server in the future.

You have now created a new mobile service that can be used by your mobile apps. Next, you will add a new table in which to store app data. This table will be used by the app in place of the in-memory collection.

Add a new tableAdd a new table to the mobile service

To be able to store app data in the new mobile service, you must first create a new table.

  1. In the Management Portal, click Mobile Services, and then click the mobile service that you just created.

  2. Click the Data tab, then click +Create.

    This displays the Create new table dialog.

  3. In Table name type TodoItem, then click the check button.

    This creates a new storage table TodoItem with the default permissions set, which means that any user of the app can access and change data in the table.

    Note

    The same table name is used in Mobile Services quickstart. However, each table is created in a schema that is specific to a given mobile service. This is to prevent data collisions when multiple mobile services use the same database.

  4. Click the new TodoItem table and verify that there are no data rows.

  5. Click the Columns tab and verify that there is only a single id column, which is automatically created for you.

    This is the minimum requirement for a table in Mobile Services.

    Note

    When dynamic schema is enabled on your mobile service, new columns are created automatically when JSON objects are sent to the mobile service by an insert or update operation.

You are now ready to use the new mobile service as data storage for the app.

Update the appUpdate the app to use the mobile service for data access

Now that your mobile service is ready, you can update the app to store items in Mobile Services instead of the local collection.

  1. If you don't already have the Mobile Services Android SDK, download it now and expand the compressed files.

  2. Copy the .jar files from the SDK into the libs folder of the GetStartedWithData project.

  3. In Package Explorer in Eclipse, right-click the libs folder, click Refresh, and the copied jar files will appear

    This adds the Mobile Services SDK reference to the workspace.

  4. Open the AndroidManifest.xml file and add the following line:

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

    This enables the app to access Mobile Services in Windows Azure.

  5. From Package Explorer, Open the TodoActivity.java file located in the com.example.getstartedwithdata package, and uncomment the following lines of code:

    import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
    import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
    import com.microsoft.windowsazure.mobileservices.NextServiceFilterCallback;
    import com.microsoft.windowsazure.mobileservices.ServiceFilter;
    import com.microsoft.windowsazure.mobileservices.ServiceFilterRequest;
    import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
    import com.microsoft.windowsazure.mobileservices.ServiceFilterResponseCallback;
    import com.microsoft.windowsazure.mobileservices.TableOperationCallback;
    import com.microsoft.windowsazure.mobileservices.TableQueryCallback;
    
    
    import java.net.MalformedURLException;
  6. We will remove the in-memory list currently used by the app, so we can replace it with a mobile service. In the ToDoActivity class, comment out the following line of code, which defines the existing toDoItemList list.

    public List<ToDoItem> toDoItemList = new ArrayList<ToDoItem>();
  7. Once the previous step is done, the project will indicate build errors. Search for the three remaining locations where the toDoItemList variable is used and comment out the sections indicated. Also remove import java.util.ArrayList. This fully removes the in-memory list.

  8. We now add our mobile service. Uncomment the following lines of code:

    private MobileServiceClient mClient;
    private private MobileServiceTable<ToDoItem> mToDoTable;
  9. In the Management Portal, click Mobile Services, and then click the mobile service you just created.

  10. Click the Dashboard tab and make a note of the Site URL, then click Manage keys and make a note of the Application key.

    You will need these values when accessing the mobile service from your app code.

  11. In the onCreate method, uncomment the following lines of code that define the MobileServiceClient variable:

    try {
    // Create the Mobile Service Client instance, using the provided
    // Mobile Service URL and key
        mClient = new MobileServiceClient(
                "MobileServiceUrl",
                "AppKey", 
                this).withFilter(new ProgressFilter());
    
    
    // Get the Mobile Service Table instance to use
    mToDoTable = mClient.getTable(ToDoItem.class);
    
    
    } catch (MalformedURLException e) {
        createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
    }

    This creates a new instance of MobileServiceClient that is used to access your mobile service. It also creates the MobileServiceTable instance that is used to proxy data storage in the mobile service.

  12. In the code above, replace MobileServiceUrl and AppKey with the URL and application key from your mobile service, in that order.

  13. Find the ProgressFilter class at the bottom of the file and uncomment it. This class displays a 'loading' indicator while MobileServiceClient is running network operations.

  14. Uncommment these lines of the checkItem method:

    mToDoTable.update(item, new TableOperationCallback<ToDoItem>() {    
        public void onCompleted(ToDoItem entity, Exception exception,
                ServiceFilterResponse response) {
            if(exception == null){
                if (entity.isComplete()) {
                    mAdapter.remove(entity);
                }
            } else {
                createAndShowDialog(exception, "Error");    
            }
        }
    });

    This sends an item update to the mobile service and removes checked items from the adapter.

  15. Uncommment these lines of the addItem method:

    mToDoTable.insert(item, new TableOperationCallback<ToDoItem>() {
    
    
    public void onCompleted(ToDoItem entity, Exception exception,
            ServiceFilterResponse response) {
        if(exception == null){
            if (!entity.isComplete()) {
                mAdapter.add(entity);
            }
        } else {
            createAndShowDialog(exception, "Error");
        }               
    }
    
    
    });

    This code creates a new item and inserts it into the table in the remote mobile service.

  16. Uncommment these lines of the refreshItemsFromTable method:

    mToDoTable.where().field("complete").eq(false)
    .execute(new TableQueryCallback<ToDoItem>() {
         public void onCompleted(List<ToDoItem> result, 
                 int count, Exception exception, 
                 ServiceFilterResponse response) {
    
    
                if(exception == null){
                    mAdapter.clear();
    
    
                    for (ToDoItem item : result) {
                        mAdapter.add(item);
                    }
                } else {
                    createAndShowDialog(exception, "Error");
                }
            }
        });

    This queries the mobile service and returns all items that are not marked as complete. Items are added to the adapter for binding.

Now that the app has been updated to use Mobile Services for backend storage, it's time to test the app against Mobile Services.

Test the appTest the app against your new mobile service

  1. From the Run menu, click Run to start the project in the Android emulator.

    This executes your app, built with the Android SDK, that uses the client library to send a query that returns items from your mobile service.

  2. As before, type meaningful text, then click Add.

    This sends a new item as an insert to the mobile service.

  3. In the Management Portal, click Mobile Services, and then click your mobile service.

  4. Click the Data tab, then click Browse.

    Notice that the TodoItem table now contains data, with id values generated by Mobile Services, and that columns have been automatically added to the table to match the TodoItem class in the app.

This concludes the Get started with data tutorial for Android.

Next steps

This tutorial demonstrated the basics of enabling an Android app to work with data in Mobile Services.

Next, consider completing one of the following tutorials that is based on the GetStartedWithData app that you created in this tutorial:

Once you have completed the data series, try these other Android tutorials: