Vous êtes sur la page 1sur 49

2012 by SAP AG. All rights reserved.

SAP and the SAP logo are registered trademarks of SAP AG in Germany and other countries. Business Objects and the Business Objects logo are trademarks or registered trademarks of Business Objects Software Ltd. Business Objects is an SAP company. Sybase and the Sybase logo are registered trademarks of Sybase Inc. Sybase is an SAP company. Crossgate is a registered trademark of Crossgate AG in Germany and other countries. Crossgate is an SAP company.

BUILDING SYNCHRONIZED MOBILE APPS WITH SYBASE UNWIRED PLATFORM


MOB262
Exercises / Solutions Speakers Name / Company

INTRODUCTION
In this exercise you will be creating a native Object API application using the Android development tools. The intention is to teach you the basics of calling the Object API. Its not intended to teach you how to develop code for Android however some knowledge of Java is required to complete this lab. In this exercise you will be creating the Mobile Business Objects (MBO) and the Android application which will take input from SAP backend and provide you the customer list details.

Concepts Covered
Creating mobile application project in Sybase Unwired Workspace Generating Object API code in Sybase Unwired Workspace Creating Object API based Android application

EXERCISE 1 - MBO DEVELOPMENT


Prerequisites
Sybase Unwired Platform 2.1.3 Server Runtime and Mobile SDK installed Android java files are copied in location < D:\Files\Session\MOB262\Project Files >

Make sure you are into the Mobile Development perspective.

Check whether the Enterprise Explorer is opened or not. Otherwise, go to menu Window->Show View-> Enterprise Explorer.

PROCEDURE
First well need to create a Mobile Application Project. 1. Start the Unwired Workspace by either selecting Start -> Programs -> Sybase -> Unwired Platform -> Unwired Workspace or double clicking the Unwired Workspace shortcut on the desktop. 2. When the Sybase Workspace starts up it will prompt for a location for the workspace where it will store all the SUP mobile projects. You can leave the default and click OK.

The first time you run Sybase Unwired Workspace it will show a welcome screen with links to different resources. Click the X beside the Welcome text to close the view.

3. We shall create a connection profile which would contain the connection parameters to connect to SAP backend In Enterprise Explorer, right-click on SAP Servers folder and select New .

In Connection Wizard, enter name for the connection SAP ERP System where description is optional, click Next

On the connection profile properties page, enter values to the required parameters

Click on the tab Test Connection. You should get Ping Succeeded. Click Finish.

A connection profile called SAP ERP System is added to the Enterprise Explorer view.

4. We shall create a Sybase Unwired Server connection profile to get connected to Unwired Server In Enterprise Explorer, right-click My Unwired Server and click Connect. If connection fails, click on properties and enter the password again Abcd1234.

Creating the MBO


Go to menu File->New->Mobile Application Project Enter project name as CustomerListMBO. Leave the workspace as default. Click Finish.

Right click on Mobile Business Objects -> New->Mobile Business Object.

Enter the name of the MBO as Customer. Click Next.

Choose data source as SAP with connection Profile as SAP ERP System. Click Next.

In the next screen you select the BAPI/RFC operation. Click on Browse and search for the RFC function module to be called.

Then click OK.

Parameter definition for BAPI Customer Getlist appears. It expects atleast one output parameter. Click on AddressData. Check the Input and output parameters by expanding the attributes.

Now click on Preview and test the function module. Enter the following values in the Input Range

Click OK. Click on Preview tab. Say yes on the dialog window.

A list of customers will appear.

Click Next.

After previewing the values now we will set the same input values as default parameters so that when the application gets loaded then the entire customer list also comes by default as per the INPUT_RANGE.

Click Next. Now this sets the Attributes Mapping between the Customer MBO and data source SAP RFC.

This MBO has no primary key hence there is a warning for Customer that it should have a primary key. Check the box for Customer attribute and mark it as primary. Itll open a dialog box and notify about the generation of object query. Say OK.

Now attribute Customer is set as primary key. Click Next.

Further click Next and Finish. MBO diagram is created. Right click and select Arrange All

Save the project. Now highlight the MBO and select the Properties tab below. You can view different properties that are set for the MBO. .

Setting the Personalization Parameter


Here we will learn how to set the personalization parameters which we will map to the load arguments. In effect, it will personalize the data being loaded from backend to CDB and CDB to device.

Steps In the workspace navigator Goto Personalization Keys Right click ->New-> Personalization Key

Fill in the details as in the screen. Click OK.

Provide the default values to the InRangePK. This is done so that incase if user doesnt input any value then the data gets loaded on the basis of this default value.

New Personalization key InRangePK appears.

Under Properties View, click on the Attributes tab in left vertical pane and Load Arguments on the right pane. You will map the Personlization key InRangePK to IDRange load argument. This means when the application would run then on the basis of user input the data will be loaded to the device otherwise it will take the default personalized data values.

Similary check out the values set for Attributes Mapping and Object Queries.

Now click Save on the upper left corner to save the MBO.

Deployment of MBO
Right Click on the MBO project and click Deploy Project.

Choose Update and click Next.

Click Next, Next.

If the connectivity to the unwired server is lost, then here we need to CONNECT again. Click Next, Next.

Create a New Server Connection..

Click OK.

Click Finish.

Deployment in progress..

You should get a successful message on completion of deployment.

EXERCISE 2 ANDROID APPLICATION DEVELOPMENT

Now we need to Generate Code from MBO project.


Right click on the Mobile Application Project and click Generate Code.

You will now create a new code generation configuration. This is useful if you are generating code for several different platforms. These settings will be set only once. On the Generate Code dialog click the Add button. On the New Configuration dialog enter Android for the Name and click OK.

The Generate Code dialog should now show the Android configuration and it should be selected. Click Next.

Click the checkbox beside Mobile Business Objects in the tree and click Next

Click Browse.

Now right click and create folder to save the generated code.

Enter name as Android as this will help to distinguish that these are Android specific generated files. Click Finish.

Once folder is formed, check the flag for Clean up destination for code generation and Uncheck for Generate Javadoc.

Click Finish.

Once MBO code is generated you should be able to see the success message.

In Workspace Navigator expand the Generated Code/Android/src/com/customerlist/mbo folder. You should see all the generated classes.

Notice that there is a red X icon beside CustomerListMBODB.java and on all the folders leading up to it. If you go to the Problems view you will see the error message.

The Eclipse environment is attempting to parse the generated Android Java code and it cannot find an Android system class referenced by the generated code. This is not an actual problem since the CustomerListMBO project is an MBO project not a Java project. This error can be ignored.

Create Android Object API Project


This exercise will guide you through the standard steps for developing an Object API based Android project. To create the Android application we need Android plugin into the eclipse. Either you can install it in SUP workspace or as a separate eclipse environment. Here we will open a separate eclipse environment. Go to Programs->Eclipse->Eclipse Indigo J2EE- MOB262

Procedure In MOB262 workspace, click File -> New -> Project. Expand the Android folder, select Android Application Project, click Next.

In the next screen fill in the Application Name, Project Name and Package name. Application name = this name is shown in the Play store and also on Manage Applications of the device Project Name = Name of your project which is only used by eclipse but must be unique within a workspace. It can be same as the application name. Package Name = It must be a unique identifier for your application. It must remain the same for the lifetime of your application. It is how the multiple versions of the same application are considered the same app.

Click Next. In this screen we need to choose the Icon for the application. Click Choose and icon of your choice. Click Next.

Click on the Blank Activity. Click Next.

Fill in the Activity name of the main activity and title. Click Finish.

You will observe a CustomerListAndroidApp project appears in the workspace navigator/package explorer.

Open up an Explorer window to <D:\SAP\Sybase\UnwiredPlatform\MobileSDK213\ObjectAPI\Android>. Select the JAR files and the armeabi folder and copy them to the libs folder of CustomerListAndroidApp Project in the workspace. The SybaseDataProvider.apk is not required.

Configure the Build Path for the Android project. Right-click on the CustomerListAndroidApp project in PackageExplorer/Workspace Navigator and select Properties, navigate to Java Build Path, go to the Libraries tab, click Add JARs.

Select the 3 JAR files added previously, and click OK.

The list should now show the 3 SUP jar files. Click OK to close the Properties for CustomerListAndroidApp dialog.

Now we further need to set some permission to the Android application. Each Android application needs to specify which permissions it requires to run. Double click on AndroidManifest.xml file to open it. Go to the tab AndroidManifest.xml and add the following XML tags after the uses-sdk tag. <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Also check whether the xml standard notations are followed or not. Please add <?xml version=1.0 encoding=utf-8?> as first line on the manifest file.

Add a Detail Activity class and CustomerListAndroidActivity to the AndroidManifest.xml file.

<activity android:name=".CustomerListAndroidActivity" android:label="@string/app_name" > </activity> <activity android:name=".DetailActivity" android:label="@string/app_name" > </activity>

The complete AndroidManifest.xml file should look like this

Now we need to copy the MBO generated code to the Android project. For that, open Windows Explorer, copy the contents of D:\Files\Session\MOB262\workspace\CustomerListMBO\Generated Code\Android\src to D:\Files\Session\MOB262\Eclipse\Workspace\CustomerListAndroidApp\src. After copying, your project should look like the screenshot below. It may take a few seconds for Eclipse to detect the new files.

At this point you have a starting point for creating an Object API based Android application. Anytime you create an Object API based Android application you will follow the above steps.

Implementing the application


Some additional classes and resource files have been provided to build a basic user interface for you. Goto location < D:\Files\Session\MOB262\Project Files> and copy files Alert.java, MainActivity.java, CustomerListAndroidActivity.java, CustomerListViewAdapter.java,DetailActivity.java and paste them under project folder CustomerListAndroidApp->src->com.customerlist, thus overwriting any existing files. Also copy the layout files customerdetail.xml, customerlist.xml, main.xml, row.xml from the same location and paste them under the folder in CustomerListAndroidApp->res->layout.

The SUP initialization code has not been provided in the MainActivity.java. The next steps will guide you through implementing that code in the initializeApplication method. Open MainActivity.java, find the initializeApplication method and type in the code in the following steps 4 to 8 under the comment that says Insert Initialization Code Here. Set the application properties: Application app = Application.getInstance(); app.setApplicationIdentifier("CustomerListMBO"); app.setApplicationContext(getApplicationContext()); CustomerListMBODB.setApplication(app); o o o o The first line gets an instance of the Application object. The second line sets the application identifier. This is typically the same name as your MBO package. This identifier is used by SUP and must match the Application ID in SCC. The third line is required only on Android. It sets the Android context which provides information about the application environment to SUP client runtime. It passes getApplicationContext which is the main application context. The fourth line links the application to the package DB class.

Set the connection properties: ConnectionProperties connProps = app.getConnectionProperties(); connProps.setServerName("<SUP Server>"); connProps.setPortNumber(5001); connProps.setLoginCredentials(new LoginCredentials("supAdmin", "Abcd1234")); CustomerListMBODB.getSynchronizationProfile().setServerName(connProps.getServerName()); o o o For the server name use either the SUP servers IP address (beware of IP address changes due to DHCP) or its hostname including DNS suffix (run ipconfig /all to get DNS suffix). The code above uses the default messaging port of 5001. If connecting through a relay server the farm ID also needs to be set. Youll need to provide credentials for logging in.

Register the connection if not registered, otherwise start the connection: if (app.getRegistrationStatus() != RegistrationStatus.REGISTERED) { app.registerApplication(300); } else { app.startConnection(60); } o The code above first checks if the device has been registered. If it has not then it performs the registration otherwise it starts the connection. The registerApplication and startConnection take an optional timeout parameter in seconds. If the registration or connection does not complete in that time then an ApplicationTimeoutException is thrown. The call will block until the registration or connection is completed or an exception occurs.

Setup the encryption properties: ConnectionProfile connProfile = CustomerListMBODB.getConnectionProfile(); connProfile.setEncryptionKey("secret"); connProfile.setCacheSize(524288); connProfile.save(); o It also allows you to set an encryption key to encrypt the database and the size of the in-memory database cache (in bytes).

Check if the default sync group has been synchronized yet. If not then perform an initial sync: if (!CustomerListMBODB.isSynchronized("default")) { CustomerListMBODB.synchronize(); } o The synchronize call will synchronize all sync groups since none is specified. If you want synchronize specific sync groups then call the overloaded synchronize method that accepts a string containing a comma delimited list of groups to sync. When the application exits, it should close the connections opened in the initializeApplication code.

Edit the public void onClick(View view) function and insert the below code under the comment Insert submit button code here. Basically we are putting the personalization code for the try block of the submit button. // create a variable of type BAPI which is mapped to personalization key in modeling and set the values BAPI_CUSTOMER_GETLIST_IDRANGE range = new BAPI_CUSTOMER_GETLIST_IDRANGE() ; range.setSIGN("I") ; range.setOPTION("BT") ; range.setHIGH(highvalue) ; range.setLOW(lowvalue) ;

// create a generic list of type BAPI and add the BAPI object to it. GenericList<BAPI_CUSTOMER_GETLIST_IDRANGE> rangeList = new GenericList<BAPI_CUSTOMER_GETLIST_IDRANGE>() ; rangeList.add( range ) ; // now set the list value inside personalization parameter. pp = CustomerListMBODB.getPersonalizationParameters(); pp.setInRangePK(rangeList); pp.save(); System.out.println("Calling synchronize second time after setting personalization parameters"); CustomerListMBODB.synchronize();

Edit the onDestroy method in CustomerListAndroidActivity.java and add code to stop the application connection and close all database connections: Application.getInstance().stopConnection(); CustomerListMBODB.closeConnection(); super.onDestroy();

Running the application


Create and define a new launch configuration for the CustomerListAndroidApp project. The configuration defines how the application launches on the target Android platform.
Prerequisites

In the Unwired WorkSpace Window menu, use the AVD Manager to add a new target Android Virtual Device (AVD) for the launch configuration.
Goto menu Windows >AVD Manager

Click New

Close the window. Now go back to the Package explorer and right click on the Android project.

Select Run As > Run Configurations. Right-click Android Application and select New. In the Name field, enter CustomerAppTest. In the Android tab, click Browse and select CustomerListAndroidApp. Click OK.

In the Launch Action area, select Launch Default Activity.

In the Target tab, select a deployment target. For example, select Automatic and the AVD that you created earlier for deployment. Keep the other default settings. Click Apply and then Close.

Testing the Device Application on the Android Emulator


Add the views monitor the application while it gets executed. Goto menu Window-> Show view -> Console, Window->ShowView->Log Cat

In Package Explorer, right-click the CustomerListAndroidApp and select Run As > Android Application

Android Emulator starts loading You can view the device messages in the Logcat view and console view

On loading the emulator -

By default the home screen opens and eventually application will open. Since we are launching the application also for first time so the emulator itself opens the application.

The application opens with the Main activity which asks for the User input. Click on the Low value. It will enable the keymap to enter the numbers.

Enter the high and low value for the range of customers whose details you would like to view. Click Submit

It now opens a personalized list of customer values belonging to the input range provided by the user. This calls the CustomerListAndroidActivity. Please note emulator might take few seconds to show the data.

Click on any customer to view the customer details. This will call the DetailActivity.