mo android mobiledata app pdf

Upload: technetvn

Post on 14-Oct-2015

36 views

Category:

Documents


0 download

DESCRIPTION

Mo Android Mobiledata App PDF

TRANSCRIPT

  • Copyright IBM Corporation 2014 TrademarksBuild an Android app using the MobileData cloud service Page 1 of 10

    Build an Android app using the MobileData cloudserviceBelinda JohnsonSoftware Engineer, IBM Mobile Cloud ServicesIBM

    Nick GibsonSoftware Engineer, IBM Mobile Cloud ServicesIBM

    Andrew HuffmanSoftware Engineer, IBM Mobile Cloud ServicesIBM

    23 May 2014(First published 20 February 2014)

    Build an Android application using the MobileData service on IBM Bluemix. This multi-partseries will gradually build, with each part introducing you to new services. This article includesa 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 servicesinto 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 thingsbetter and easier to use! We'll do our best to keep this article up to date, but it will not always beperfectly aligned. Thanks for understanding!

    You may already know about some of the benefits of Bluemix, IBM's open platform for developingand deploying mobile and web applications. The many pre-built services in Bluemix make it easyfor developers to build and enhance applications. In this article, we'll cover the steps to build anAndroid application using the MobileData service.

    Have you ever gone to the grocery store and forgotten the exact ingredient your spouse neededfor 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 pushnotifications 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 youstarted writing your own (more complex) apps in no time! This article shows you how to startwith an Android application and add the MobileData service to store, delete, update, and queryobjects stored on the cloud. (A future article will show you how to add the Push and Node.js Cloudservices to your application so you can get notifications when the grocery list is updated, and sothe 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 youstarted writing your own (more complex) apps in no time.

    Get bluelist-base(v0) codeGet bluelist-mobiledata(v1) codeThe bluelist-base(v0) code is the base version of the BlueList app. We'll show you how to addthe MobileData service, so that your code will look like the bluelist-mobiledata(v1) code. You canstart 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 theMobileData 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 thisarticle will show you how to add the MobileData service to your app, so that list items willpersist.

    A Bluemix ID (join the beta!), so you can get the MobileData service.

    Step 1. Create a Mobile Cloud application on Bluemix1. 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 foryour app. Then click Create.

    6. After you create the application, it will appear in your dashboard. Click your new application togo 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 thebluelist.properties file in the assets folder of your project. (To get to the Overview page, login to Bluemix, go to your Dashboard, and click the desired application.) The properties file isused to load important external data. You are not tied to using a properties file and can useany model you prefer.applicationID=

    Step 2. Add basic permissions1. 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.

    Step 3. Edit the BlueListApplication to initialize the SDK and serviceas well as register the Item specialization with the MobileDataservice

    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(); // 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 theItem specialization. Make these edits in the onCreate method, immediately after reading theproperties file, as shown below:// Initialize the SDK, initialize the service and register the Item specializationIBMBaaS.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 willautomatically import any required elements from the SDK jars you copied into the projectearlier. You may still see some errors at this point, but these should be resolved as youcontinue with these instructions.

    Step 4. Edit the Item class to use the MobileData service1. 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 beused 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 availablegetObject and setObject methods. Values associated with an object are referenced bya key. You may set values using setObject(, ), and retrieve them usinggetObject().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, anddelete data in the cloud

    1. Implement the listItems method to read items from MobileData. We will sort these items incase-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 query = IBMQuery.queryForClass(Item.class); query.findObjectsInBackground(new IBMQueryResult() { public void onResult(final List 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 listwith 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() { 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'sdeleteInBackground 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() { //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 theMobileData service

    1. The finishedEdit method will call MobileData's saveInBackground. Implement onResult andonError.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() { 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 app1. 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 ofhow 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/)

    Table of ContentsWhat you'll need for your applicationStep 1. Create a Mobile Cloud application on BluemixStep 2. Add basic permissionsStep 3. Edit the BlueListApplication to initialize the SDK and service as well as register the Item specialization with the MobileData serviceStep 4. Edit the Item class to use the MobileData serviceStep 5. In the MainActivity class, use MobileData to create, read, and delete data in the cloudStep 6. In the EditActivity class, update data on the cloud using the MobileData serviceStep 7. Run the appStep 8. See your data on the cloudConclusionAbout the authorsTrademarks