Build an Android app using the MobileData cloud service

27 June 2014
PDF (661 KB)
 

Build an Android app using the MobileData cloud service

11:21  |  Transcript
author photo - belinda johnson

Belinda Johnson

Software Engineer, IBM Mobile Cloud Services

@BeeMarieJohnson

author photo - nick gibson

Nick Gibson

Software Engineer, IBM Mobile Cloud Services

 

author photo - andrew huffman

Andrew Huffman

Software Engineer, IBM Mobile Cloud Services

 

Sign up for IBM Bluemix
This cloud platform is stocked with free services, runtimes, and infrastructure to help you quickly build and deploy your next mobile or web application.

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?

Enter the BlueList application. It’s 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.

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, 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. Screen shot of the Create an Application button
  3. Click Mobile Cloud, under Boilerplates. Screen shot of the Mobile Cloud boilerplate
  4. Click Create Application. Screen shot of the Mobile Cloud Application with the create application button
  5. Fill in the "Finish Adding Mobile Cloud " panel by selecting a space and choosing a name for your app. Then click Create. Screen shot of the app creation panel
  6. After you create the application, it will appear in your dashboard. Click your new application to go to its Overview page. Screen shot of the Application in the Catalog
  7. You will see the Overview for your new application. Once there, click Download SDKs.
    Screen shot of the Download SDKs button

    Click to see larger image

    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.Screen shot of the Download SDKs button

    Click to see larger image

  9. Unzip the SDK that you just downloaded, and copy the required jars (ibmbluemix.jar, ibmdata.jar, and ibmfilesync.jar) into the libs folder of your bluelist-android-base project.Screen shot of the jar files going into the project
  10. Copy the applicationID, applicationSecret, and applicationRoute values to the bluelist.properties file in the assets folder of your project. The applicationRoute and applicationID values are available on your application's Overview page. The applicationSecret is only available on your application's Mobile Application Security page. To get these values, log in to Bluemix, go to your Dashboard, and click the desired application. The applicationRoute and applicationID values will be visible at the top of the Overview page. Click on the Mobile Application Security link in the navigation area to get the applicationSecret value. The properties file is used to load important external data.
    					applicationID=<INSERT_APPLICATION_ID_HERE>
    					applicationSecret=<INSERT_APPLICATION_SECRET_HERE>
    					applicationRoute=<INSERT_APPLICATION_ROUTE_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 APP_SECRET = "applicationSecret";
    	private static final String APP_ROUTE = "applicationRoute";
    	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:
    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 IBM core backend-as-a-service
    IBMBluemix.initialize(this, props.getProperty(APP_ID), 
    					props.getProperty(APP_SECRET), props.getProperty(APP_ROUTE));
    // initialize the IBM Data Service
    IBMData.initializeService();
    // register the Item Specialization
    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.

    Click to see code listing

    public void listItems() {
    	try {
    		IBMQuery<Item> query = IBMQuery.queryForClass(Item.class);
    		// Query all the Item objects from the server
    		query.find().continueWith(new Continuation<List<Item>, Void>() {
    
    			@Override
    			public Void then(Task<List<Item>> task) throws Exception {
    				// Log error message, if the save task fail.
    				if (task.isFaulted()) {
    					Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    					return null;
    				}
    				final List<Item> objects = task.getResult();
    				
    				 // If the result succeeds, load the list
    				if (!isFinishing()) {
    					runOnUiThread(new Runnable() {
    						public void run() {
    							//clear local itemList
    							//we'll be reordering and repopulating from DataService
    							itemList.clear();
    							for(IBMDataObject item:objects) {
    								itemList.add((Item) item);
    							}
    							sortItems(itemList);
    							lvArrayAdapter.notifyDataSetChanged();
    						}
    					});
    				}
    				return null;
    			}
    		});
    			
    	}  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 MobileData’s 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);
    		// Use the IBMDataObject to create and persist the Item object 
    		item.save().continueWith(new Continuation<IBMDataObject, Void>() {
    
    			@Override
    			public Void then(Task<IBMDataObject> task) throws Exception {
    
    				// Log error message, if the save task fail.
    				if (task.isFaulted()) {
    					Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    					return null;
    				}
    
    				 // If the result succeeds, load the list
    				if (!isFinishing()) {
    					listItems();
    				}
    				return null;
    			}
    
    		});
    			
    		//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.delete().continueWith(new Continuation<IBMDataObject, Void>() {
    
    		@Override
    		public Void then(Task<IBMDataObject> task) throws Exception {
    
    		// Log error message, if the delete task fail.
    		if (task.isFaulted()) {
    			Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    			return null;
    		}
    
    		// If the result succeeds, reload the list
    		if (!isFinishing()) {
    			runOnUiThread(new Runnable() {
    				public void run() {
    					lvArrayAdapter.notifyDataSetChanged();
    				}
    			});
    		}
    			return null;
    		}
    	});
    	
    	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 save(). Implement using Bolts continueWith() and Continuation task.

    Click to see code listing

    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.save().continueWith(new Continuation<IBMDataObject, Void>() {
    		@Override
    		public Void then(Task<IBMDataObject> task) throws Exception {
    			
    			if (task.isFaulted()) {
    				Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    				return null;
    			}
    			
    			if (!isFinishing()) {
    				runOnUiThread(new Runnable() {
    					public void run() {
    						Intent returnIntent = new Intent();
    						setResult(BlueListApplication.EDIT_ACTIVITY_RC, returnIntent);
    						finish();
    					}
    				});
    			}
    			
    			return null;
    		}
    	});
    }

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.
     Screen shot of the first page of BlueList app
  3. Add some grocery list items.
     
    Screen shot of adding some grocerylist itemsScreen shot of adding some grocerylist 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. Screen shot of data viewer
  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. Screen shot of analytics statistics and graphics

    Click to see larger image

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

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Mobile development, Cloud computing
ArticleID=963125
ArticleTitle=Build an Android app using the MobileData cloud service
publish-date=06272014