To celebrate the Mobile Services Android launch, I’ve decided to put together a blog series over the next week to highlight some of the cool new features in our Android SDK. Here is the list of subjects I plan to cover:
- Working with typed and untyped data
- Customizing serialization using the gson library
- Exploring the richness of the query model
- Implementing authentication correctly
- Intercepting HTTP traffic for fun and profit
- Unit testing your client code
- Advanced push scenarios
Today, let’s focus on the data access aspect of the client, which lets us work with server entities in a typed or untyped way. Let’s start with a simple class that we want to store in a server-side table. We’re naming our class and properties to resemble the serialized JSON, we will cover how to customize the mapping between the properties and the serialized representation in a later post.
public class droid {
public int id;
public String name;
public Float weight;
public Integer numberOfLegs;
public Integer numberOfWheels;
}
Note that a phantom menace lurks here: the class needs to contain a property called Id, ID, or id which will be populated by the server when it stores the entity.
To store instances of the class inside Mobile Services, we first need to create our Mobile Service in the Azure portal and then create a table called droid. Capitalization is important here. We then use the URL and application key provided in the portal to instantiate the MobileServiceClient.
MobileServiceClient client = new MobileServiceClient(
"https://droid.azure-mobile.net/",
"RrBQdeuaScZCIUsDSNnHPUyKowDDdW89",
this);
The third parameter we pass here is the Activity or Service where the client is instantiated. We use that reference to grab the application context, which we use to store the installation ID for this application and also to display our authentication UI dialog.
Now we need to get a reference to the table object so we can insert data into it. Let’s look at the different overloads of the getTable method.
public class MobileServiceClient {
public MobileServiceJsonTable getTable(String name);
public <E> MobileServiceTable<E> getTable(String name, Class<E> clazz);
public <E> MobileServiceTable<E> getTable(Class<E> clazz);
}
The first overload is for working with our untyped JSON-based programming model, we will discuss that in a second. The second overload lets you work with a table if its name is different from the type name. The last overload assumes the class name and the table name are the same; this is the simplest one and that’s what we’ll use here.
MobileServiceTable<droid> table = client.getTable(droid.class);
We can then instantiate a new instance of the droid class and insert it into our server-side table.
~~~ java droid r2d2 = new droid(); r2d2.name = “R2D2”; r2d2.numberOfLegs = 0; r2d2.numberOfWheels = 2; r2d2.weight = 432.21f;