Build an Android app using the IBM Mobile Data for Bluemix cloud service

Store, delete, update, and query objects stored in the cloud

14 August 2014
PDF (673 KB)
Share:

Build an Android app using the IBM Mobile Data for Bluemix 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

@ndgibs on Twitter
Follow me on Google+

author photo - andrew huffman

Andrew Huffman

Software Engineer, IBM Mobile Cloud Services

 

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 the Mobile services in Bluemix make it easy for developers to build and enhance applications.

Tutorials in this series show you how to add cloud-based services to your apps. In this tutorial, we'll cover the steps to build an Android application using the IBM Mobile Data for Bluemix service.

WATCH:Webcast: Building an Android App using MobileData Cloud

Have you ever gone to the grocery store and forgotten the exact ingredient your spouse needed for that fabulous soufflé recipe? Or the lunch box 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 tutorial shows you how to start with an Android application and add the IBM Mobile Data for Bluemix service to store, delete, update, and query objects stored on the cloud. (A future tutorial 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 IBM Mobile Data for Bluemix 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 IBM Mobile Data for Bluemix 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.

    Note: If you decide to use Android Studio you can skip Steps 1.7-1.9 since the gradle.build file provided in the Android root directory will pull in the required dependencies. Please check it out, familiarize yourself with the Gradle build code, and uncomment the required dependencies. You will also need to download the Gradle.zip and extract the contents to the directory of your choice. When Android Studio prompts you for a GRADLE_HOME, use the path you extracted the .zip to, where the bin directory lives.

  • 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 tutorial will show you how to add the IBM Mobile Data for Bluemix service to your app, so that list items will persist.
  • A Bluemix ID, so you can use the IBM Mobile Data for Bluemix service.

READ:Getting started with Mobile Data

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. (Skip if using Android Studio)
    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. (Skip if using Android Studio)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. (Skip if using Android Studio)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 IBM Mobile Data for Bluemix 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 IBM Mobile Data for Bluemix service

 
  1. Integrate the IBM Mobile Data for Bluemix service by extending Mobile Data'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 Mobile Data 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 the IBM Mobile Data for Bluemix service to create, read, and delete data in the cloud

 
  1. Implement the listItems method to read items from the IBM Mobile Data for Bluemix service. We will sort these items in case-insensitive alphabetical order. Create listItems as a method of the MainActivity 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 {
                        final List<Item> objects = task.getResult();
                         // Log if the find was cancelled.
                        if (task.isCancelled()){
                            Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
                        }
    					 // Log error message, if the find task fails.
    					else if (task.isFaulted()) {
    						Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    					}
    
    					
    					 // If the result succeeds, load the list.
    					else {
                            // 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;
    				}
    			},Task.UI_THREAD_EXECUTOR);
    			
    		}  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 the IBM Mobile Data for Bluemix service.
    itemsLV.setAdapter(lvArrayAdapter);
    
    /* Refresh the list. */
    listItems();
  3. Change the createItem method to create new items using an instance of the IBMDataObject class. Call Mobile Data’s save() method on the instance and use the continueWith() method to handle any errors or load the updated list.

    Click to see code listing

    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 if the save was cancelled.
    				if (task.isCancelled()){
    					Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
    				}
    				 // Log error message, if the save task fails.
    				else if (task.isFaulted()) {
    					Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    				}
    
    				 // If the result succeeds, load the list.
    				else {
    					listItems();
    				}
    				return null;
    			}
    
    		});
    		
    		// Set text field back to empty after item is added.
    		itemToAdd.setText("");
    	}
    }
  4. Make some changes to the deleteItem method. It will now call Mobile Data's delete() method on an instance of the IBMDataObject class. The delete() method returns a Bolts Task which is used to check for the success or failure of the task.

    Click to see code listing

    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 if the delete was cancelled.
    			if (task.isCancelled()){
    				Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
    			}
    
    			 // Log error message, if the delete task fails.
    			else if (task.isFaulted()) {
    				Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    				}
    
    			 // If the result succeeds, reload the list.
    			else {
    				lvArrayAdapter.notifyDataSetChanged();
    			}
    			return null;
    		}
    	},Task.UI_THREAD_EXECUTOR);
    	
    	lvArrayAdapter.notifyDataSetChanged();
    }

Step 6. In the EditActivity class, update data on the cloud using the the IBM Mobile Data for Bluemix service

 
  1. The finishedEdit method will call Mobile Data's save() method on the instance of the IBMDataObject to be updated. Implement using the continueWith() method to handle any errors.
    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.isCancelled()) {
    				Log.e(CLASS_NAME, "Exception : " + task.toString() + " was cancelled.");
    			}
    
    			else if (task.isFaulted()) {
    				Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
    			}
    			
    			else {
    				Intent returnIntent = new Intent();
    				setResult(BlueListApplication.EDIT_ACTIVITY_RC, returnIntent);
    				finish();
    			}
    			return null;
    		}
    		
    	},Task.UI_THREAD_EXECUTOR);
    
    }

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 Mobile Data 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 IBM Mobile Data service in Bluemix should give you a sense of how easy it is to consume and integrate mobile data capabilities using mobile cloud services!


BLUEMIX SERVICE USED IN THIS TUTORIAL:IBM Mobile Data for Bluemix (powered by Cloudant) provides simple-to-use SDKs that provide access to a scalable, fully managed database via familiar object-oriented APIs.

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 IBM Mobile Data for Bluemix cloud service
publish-date=08142014