Você está na página 1de 10

Copyright IBM Corporation 2014 Trademarks

Build an Android app using the MobileData cloud service Page 1 of 10


Build an Android app using the MobileData cloud
service
Belinda Johnson
Software Engineer, IBM Mobile Cloud Services
IBM
Nick Gibson
Software Engineer, IBM Mobile Cloud Services
IBM
Andrew Huffman
Software Engineer, IBM Mobile Cloud Services
IBM
23 May 2014
(First published 20 February 2014)
Build an Android application using the MobileData service on IBM Bluemix. This multi-part
series will gradually build, with each part introducing you to new services. This article includes
a demo, sample code, and complete instructions for creating the BlueList Android application.
You can apply what you've learned to integrate MobileData, Push, and Node.js Cloud services
into your own applications.
To view the introductory video Build an Android app using the MobileData cloud service
please access the online version of the article.
IBM Bluemix is a beta-level product, and it will be changing as we continually make things
better and easier to use! We'll do our best to keep this article up to date, but it will not always be
perfectly aligned. Thanks for understanding!
You may already know about some of the benefits of Bluemix, IBM's open platform for developing
and deploying mobile and web applications. The many pre-built services in Bluemix make it easy
for developers to build and enhance applications. In this article, we'll cover the steps to build an
Android application using the MobileData service.
Have you ever gone to the grocery store and forgotten the exact ingredient your spouse needed
for that fabulous souffl recipe? Or the lunchbox dessert the kids had requested for the next day?
What if they all could enter their requests into a shared grocery list, and you could receive push
notifications alerting you to the updates?
developerWorks ibm.com/developerWorks/
Build an Android app using the MobileData cloud service Page 2 of 10
Enter the BlueList application. Its a simple app that uses Bluemix services and will get you
started writing your own (more complex) apps in no time! This article shows you how to start
with an Android application and add the MobileData service to store, delete, update, and query
objects stored on the cloud. (A future article will show you how to add the Push and Node.js Cloud
services to your application so you can get notifications when the grocery list is updated, and so
the list can be refreshed on all devices when one of the devices updates the list in some way.)
This simple app uses Bluemix services and will get you
started writing your own (more complex) apps in no time.
Get bluelist-base(v0) code
Get bluelist-mobiledata(v1) code
The bluelist-base(v0) code is the base version of the BlueList app. We'll show you how to add
the MobileData service, so that your code will look like the bluelist-mobiledata(v1) code. You can
start with bluelist-base(v0) and walk through the steps, or jump ahead by downloading bluelist-
mobiledata(v1) directly. The bluelist-mobiledata(v1) version of the BlueList app includes the
MobileData service.
What you'll need for your application
Familiarity with Android development.
An Android development environment. We used Eclipse with ADT, but feel free to use your
preference.
The bluelist-base(v0) code. Click the button above, then import and build the bluelist-android-
base code into your Android development environment. Run this code in your emulator.
Restart the application, and notice that the list items do not not persist. The steps in this
article will show you how to add the MobileData service to your app, so that list items will
persist.
A Bluemix ID (join the beta!), so you can get the MobileData service.
Step 1. Create a Mobile Cloud application on Bluemix
1. Log in to Bluemix.
2. Click Add an application to go to the catalog.
3. Click Mobile Cloud, under Boilerplates.
4. Click Create Application.
ibm.com/developerWorks/ developerWorks
Build an Android app using the MobileData cloud service Page 3 of 10
5. Fill in the "Finish Adding Mobile Cloud " panel by selecting a space and choosing a name for
your app. Then click Create.
6. After you create the application, it will appear in your dashboard. Click your new application to
go to its Overview page.
7. You will see the Overview for your new application. Once there, click Download SDKs.
Note: You'll need this Application ID later in these instructions.
8. You will see the documentation for building a mobile application. Once there, click Android
SDK.
developerWorks ibm.com/developerWorks/
Build an Android app using the MobileData cloud service Page 4 of 10
9. Unzip the SDK that you just downloaded, and copy the required jars (ibmbaas.jar, ibmdata.jar,
and ibmfilesync.jar) into the libs folder of your bluelist-android-base project.
10. Copy the Application ID from your application's Overview page (on Bluemix) to the
bluelist.properties file in the assets folder of your project. (To get to the Overview page, log
in to Bluemix, go to your Dashboard, and click the desired application.) The properties file is
used to load important external data. You are not tied to using a properties file and can use
any model you prefer.
applicationID=<INSERT_APPLICATION_ID_HERE>
Step 2. Add basic permissions
1. Your Android app will need basic network capability and permissions, so we've included the
following permissions in the manifest file. Open up the AndroidManifest.xml file to take a look.
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.WAKE_LOCK" />
<uses-permission
android:name="android.permission.GET_ACCOUNTS" />
<uses-permission
android:name="android.permission.USE_CREDENTIALS" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE" />
Step 3. Edit the BlueListApplication to initialize the SDK and service
as well as register the Item specialization with the MobileData
service
1. Define a couple of constants for use in reading from the bluelist.properties file.
public final class BlueListApplication extends Application {
private static final String APP_ID = "applicationID";
private static final String PROPS_FILE = "bluelist.properties";
2. On creation of the application, read from the bluelist.properties file to get the Application ID.
Make these edits in the onCreate method as shown below:
ibm.com/developerWorks/ developerWorks
Build an Android app using the MobileData cloud service Page 5 of 10
public void onCreate() {
super.onCreate();
itemList = new ArrayList<Item>();
// Read from properties file
Properties props = new java.util.Properties();
Context context = getApplicationContext();
try {
AssetManager assetManager = context.getAssets();
props.load(assetManager.open(PROPS_FILE));
Log.i(CLASS_NAME, "Found configuration file: " + PROPS_FILE);
} catch (FileNotFoundException e) {
Log.e(CLASS_NAME, "The bluelist.properties file was not found.", e);
} catch (IOException e) {
Log.e(CLASS_NAME, "The bluelist.properties file could not be read properly.", e);
}
}
3. On creation of the Android application, initialize the SDK, initialize the service, and register the
Item specialization. Make these edits in the onCreate method, immediately after reading the
properties file, as shown below:
// Initialize the SDK, initialize the service and register the Item specialization
IBMBaaS.initializeSDK(this, props.getProperty(APP_ID));
IBMData.initializeService();
Item.registerSpecialization(Item.class);
4. Don't forget to use Eclipse to organize imports (Ctrl+Shift+O) as you go. This will
automatically import any required elements from the SDK jars you copied into the project
earlier. You may still see some errors at this point, but these should be resolved as you
continue with these instructions.
Step 4. Edit the Item class to use the MobileData service
1. Integrate the MobileData service by extending MobileData's IBMDataObject and annotating
this class as an IBMDataObjectSpecialization. Be sure to add a NAME string, which will be
used later as a key for accessing objects.
@IBMDataObjectSpecialization("Item")
public class Item extends IBMDataObject {
public static final String CLASS_NAME = "Item";
private static final String NAME = "name";
2. Edit the getName() and setName() methods to use the MobileData service's available
getObject and setObject methods. Values associated with an object are referenced by
a key. You may set values using setObject(<key>, <value>), and retrieve them using
getObject(<key>).
public String getName() {
return (String) getObject(NAME);
}
public void setName(String itemName) {
setObject(NAME, (itemName != null) ? itemName : "");
}
3. Remove the Item constructor as it is no longer necessary.
4. Again, organize your imports!
Step 5. In the MainActivity class, use MobileData to create, read, and
delete data in the cloud
1. Implement the listItems method to read items from MobileData. We will sort these items in
case-insensitive alphabetical order. Create listItems as a method of the Main Activity class.
public void listItems() {
developerWorks ibm.com/developerWorks/
Build an Android app using the MobileData cloud service Page 6 of 10
try {
IBMQuery<Item> query = IBMQuery.queryForClass(Item.class);
query.findObjectsInBackground(new IBMQueryResult<Item>() {
public void onResult(final List<Item> objects) {
if (!isFinishing()) {
runOnUiThread(new Runnable() {
public void run() {
//clear local itemList, as we'll be
//repopulating & reordering from MobileData.
itemList.clear();
for(IBMDataObject item:objects) {
itemList.add((Item) item);
}
sortItems(itemList);
lvArrayAdapter.notifyDataSetChanged();
}
});
}
}
public void onError(IBMDataException error) {
Log.e(CLASS_NAME, "Exception : " + error.getMessage());
}
});
} catch (IBMDataException error) {
Log.e(CLASS_NAME, "Exception : " + error.getMessage());
}
}
2. After setting the ArrayAdapter in the onCreate method, call listItems() to populate the list
with items already stored using MobileData.
itemsLV.setAdapter(lvArrayAdapter);
listItems();
3. Change the createItem method to create new items with MobileDatas saveInBackground.
Implement the onResult and onError methods.
public void createItem(View v) {
EditText itemToAdd = (EditText) findViewById(R.id.itemToAdd);
String toAdd = itemToAdd.getText().toString();
Item item = new Item();
if (!toAdd.equals("")) {
item.setName(toAdd);
item.saveInBackground(new IBMObjectResult<Item>() {
public void onResult(Item object) {
if (!isFinishing()) {
listItems();
}
}
public void onError(IBMDataException error) {
Log.e(CLASS_NAME, "Exception : " + error.getMessage());
}
});
//set text field back to empty after item added
itemToAdd.setText("");
}
}
4. Make some changes to the deleteItem method. It will now use MobileData's
deleteInBackground method. Implement onResult and onError.
public void deleteItem(Item item) {
itemList.remove(listItemPosition);
//This will attempt to delete the item on the server
item.deleteInBackground(new IBMObjectResult<Item>() {
//Called if the object was successfully deleted
public void onResult(Item item) {
if (!isFinishing()) {
runOnUiThread(new Runnable() {
ibm.com/developerWorks/ developerWorks
Build an Android app using the MobileData cloud service Page 7 of 10
public void run() {
lvArrayAdapter.notifyDataSetChanged();
}
});
}
}
//Called if there was an error deleting the item
public void onError(IBMDataException error) {
Log.e(CLASS_NAME, "Exception : " + error.getMessage());
//add error handling here.
}
});
lvArrayAdapter.notifyDataSetChanged();
}
Step 6. In the EditActivity class, update data on the cloud using the
MobileData service
1. The finishedEdit method will call MobileData's saveInBackground. Implement onResult and
onError.
public void finishedEdit(View v) {
Item item = itemList.get(location);
EditText itemToEdit = (EditText) findViewById(R.id.itemToEdit);
String text = itemToEdit.getText().toString();
item.setName(text);
item.saveInBackground(new IBMObjectResult<Item>() {
public void onResult(Item object) {
if (!isFinishing()) {
runOnUiThread(new Runnable() {
public void run() {
Intent returnIntent = new Intent();
setResult(BlueListApplication.EDIT_ACTIVITY_RC,
returnIntent);
finish();
}
});
}
}
public void onError(IBMDataException error) {
Log.e(CLASS_NAME, "Exception : " + error.getMessage());
}
});
}
Step 7. Run the app
1. Now that you've made all the code changes, your code should now be equivalent to the
bluelist-mobiledata (v1) code, and your list items should persist!
2. Run the up-to-date code in your emulator (Nexus 7 or Galaxy Nexus works well) or on your
device. Click Run > Run As > Android Application.

developerWorks ibm.com/developerWorks/
Build an Android app using the MobileData cloud service Page 8 of 10
3. Add some grocery list items.

4. Restart the application.
5. Notice that your data items have persisted. You now have data on the cloud!
Step 8. See your data on the cloud
1. Log in to Bluemix.
2. Click your application in the Dashboard view.
3. Click the MobileData Service.
4. On the Manage Data tab, you can see Data Classes being stored in the cloud, as well as the
instances of each Data Class being persisted.
5. On the Analytics tab, you can see various analytics data for your application,
including total API calls by device, API calls by type, and amount of storage used.
ibm.com/developerWorks/ developerWorks
Build an Android app using the MobileData cloud service Page 9 of 10
Conclusion
Developing this app using the MobileData service available in Bluemix should give you a sense of
how easy it is to consume and integrate mobile data capabilities using mobile cloud services!
RELATED TOPICS: Next: Add the Push and Node.js Cloud services
developerWorks ibm.com/developerWorks/
Build an Android app using the MobileData cloud service Page 10 of 10
About the authors
Belinda Johnson
@BeeMarieJohnson
Nick Gibson

Andrew Huffman

Copyright IBM Corporation 2014
(www.ibm.com/legal/copytrade.shtml)
Trademarks
(www.ibm.com/developerworks/ibm/trademarks/)

Você também pode gostar