Oracle by Example brandingInstrument an App for OMCe Analytics

Ready to get started?

In order to collect analytics for your apps, you first need to use Oracle Mobile Cloud Enterprise's SDK to add tracking code to log the events that business analysts on your team are interested in evaluating.

This tutorial demonstrates how that tracking code works via the sample EasyShopping app for the iOS, Android, and Cordova platforms.

section 1Download and set up the EasyShopping app

  1. Go to the Oracle Technology Network’s Oracle Mobile Cloud Enterprise Downloads page and download the samples zip for your preferred platform.
  2. Extract the contents of the zip on your system.
  3. Within the folder for the EasyShopping sample, open up the README.md file and follow the instructions for setting up the app on your system.

section 2Fill in the app's configuration file

So that your app can communicate with OMCe, you need to have the app registered in OMCe and then copy the application info and credentials to an SDK configuration file in your app.

The EasyShopping app should already be registered in OMCe, so you just need to get the info for the configuration file:

  1. Open your OMCe Analytics instance.
  2. In the OMCe Analytics instance, make sure that the EasyShopping app is open.

    The name of the currently open application appears in the top left of the window.

    If it is not open, click the dropdown arrow that appears to the right of the name of the currently open app and select EasyShopping.

    Screenshot showing the application picker dropdown arrow
  3. Click menu icon in the upper left corner of the page and select Settings > Application.

    Keep this page open.

Here's how you fill in the configuration file for the different platforms.

Android

  1. In the app, navigate to and open EasyShopping/app/src/main/assets/oracle_mobile_cloud_config.xml.
  2. Replace the contents of these elements with the corresponding values from the Settings > Application page:
    • oAuthTokenEndPoint - value of OAuth Token Endpoint
    • baseURL - value of Collector URL
    • appKey - value of Application Key
    • clientID - value of Client ID
    • clientSecret - value of Client Secret

iOS

  1. In the app, navigate to and open EasyShopping/EasyShopping/OMC.plist.
  2. Replace the contents of these keys with the corresponding values values from the Settings > Application page:
    • oAuthTokenEndPoint - value of OAuth Token Endpoint
    • baseURL - value of Collector URL
    • appKey - value of Application Key
    • clientId - value of Client ID
    • clientSecret - value of Client Secret

Cordova

  1. In the app, navigate to and open easy-shopping/src/mcs-config.ts.
  2. Replace the value of the oAuthTokenEndPoint property with the value of OAuth Token Endpoint you obtained from the Settings > Application page.
  3. Within the analyticsApp section of the file, replace the contents of these properties with the corresponding values from the Settings > Application page:
    • baseURL - value of Collector URL
    • appKey - value of Application Key
    • clientID - value of Client ID
    • clientSecret - value of Client Secret

section 3Browse the event-tracking code

The samples are already instrumented with app tracking code. Here are some of the highlights for each platform.

Android

Using a CxaAnalytics object to set up tracking

  • An AnalyticsApp object is used to get the analytics app configuration.
  • A CxaAnalytics object is used to track any events that you want to monitor and send the data on the recorded events to OMCe.

The tracker is instantiated in EasyShopping/app/src/main/java/com/easyshopping/demoapp/LoginActivity.java. Here are some excerpts from that file.

import oracle.cloud.mobile.analytics.AnalyticsApp;
import oracle.cloud.mobile.config.AnalyticsBaseConfig;
import oracle.cloud.mobile.exception.ServiceProxyException;
import oracle.cloud.mobile.mobilebackend.MobileManager;

import oracle.cloud.mobile.cxa.api.CxaAnalytics;

...
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks {

...
    AnalyticsApp analyticsApp;
    CxaAnalytics cxaAnalytics;

...

        try {
            analyticsApp = MobileManager.getManager().getAnalyticsApp(this);
        } catch (ServiceProxyException e) {
            e.printStackTrace();
        }

        cxaAnalytics  = analyticsApp.getServiceProxy(CxaAnalytics.class);
...
}

Event Tracking

With the CxaAnalytics object instantiated, you can define events to be tracked and have occurrences of those events logged.

EasyShopping tracks both standard event types (like screen views and e-commerce transactions) and custom-defined event types.

Let's take a look at some events that are defined in EasyShopping/app/src/main/java/com/easyshopping/demoapp/ReviewCart.java.

import oracle.cloud.mobile.cxa.api.CxaAnalytics;
import oracle.cloud.mobile.cxa.core.events.CustomEvent;
import oracle.cloud.mobile.cxa.core.events.EcommerceTransactionEvent;
import oracle.cloud.mobile.cxa.core.events.EcommerceTransactionItemEvent;
import oracle.cloud.mobile.cxa.core.events.ScreenViewEvent;

...

public class ReviewCart extends AppCompatActivity {
    ....
    private CxaAnalytics cxaAnalytics;
	
		...

    protected void onCreate(Bundle savedInstanceState) {
		...
        ScreenViewEvent svEvent = ScreenViewEvent.builder().name(getApplication()
		        .getApplicationInfo().name+" "+ TAG + " view").id("1").build();

        cxaAnalytics.logEvent(svEvent);	
    }		

    public void checkoutButtonClick(View view) {
        CustomEvent customEvent = CustomEvent.builder().category("Easy Shopping APP")
		           .action("Checkout Cart button is pressed, Navigating to Finish Activity from Review Cart")
			       .label(TAG).build();

        cxaAnalytics.logEvent(customEvent);
        placeOrder();
    }		

    public void placeOrder() {
	
        List items = Cart.getCart().getCartItemsList();

       EcommerceTransactionItemEvent ecommerceTransactionItem;
        List ecommerceTransactionItems = new ArrayList<>();

        CartItem item;
        for(int i=0;iecommerceTransactionItem = EcommerceTransactionItemEvent.builder()
                    .itemId(item.getId())
                    .sku(item.getDepId())
                    .price(item.getPrice())
                    .quantity(item.getQuantity())
                    .name(item.getTitle())
                    .category(Store.getStore().getDepartmentName(item.getDepId()))
                    .currency("USD")
                    .build();
            ecommerceTransactionItems.add(ecommerceTransactionItem);

        }
        Store.getStore().getCxaAnalytics().logEvent(EcommerceTransactionEvent.builder()
                .orderId("DemoOrderId")
                .totalValue(Cart.getCart().getPrice())
                .city("San Francisco")
                .state("CA")
                .country("USA")
                .currency("USD")
                .items(ecommerceTransactionItems)
                .build());

    }
}

You can find event logging in these classes as well:

  • BrowseActivity.java
  • CartAdapter.java
  • DisplayCart.java
  • FinishActivity.java
  • ItemAdapter.java
  • ProductDescription.java
  • LoginActivity.java

iOS

Using an OMCCxaAnalytics object to set up tracking

With the following line of code in EasyShopping/EasyShopping/ViewController.m, an OMCCxaAnalytics object is created to track and send any logged events:

OMCCxAAnalytics * analytics = [OMCMobileManager sharedManager].analyticsApp.analytics;

Event Tracking

With the OMCCxaAnalytics object instantiated, you can define events to be tracked and have occurrences of those events logged.

Within EasyShopping/EasyShopping/ViewController.m, there are screen view, custom, page view, and e-commerce events defined. Let's take a look at the code for defining and logging those events:

        OMCCxAScreenViewEvent *event1 = [OMCCxAScreenViewEvent build:^(id builder) {
            [builder setName:@"CxaName"];
            [builder setId:@"CxaScreenId"];
        }];
        
        [analytics logEvent: (OMCCxAScreenViewEvent *)event1];
        
        OMCCxACustomEvent *event2 = [OMCCxACustomEvent build:^(id builder) {
            [builder setCategory:@"CxaCategory"];
            [builder setAction:@"CxaAction"];
            [builder setLabel:@"CxaLabel"];
            [builder setProperty:@"CxaProperty"];
            [builder setValue:5];
            [builder setCustomField:@"key" andValue:@"value"];
        }];
        
        [analytics logEvent: (OMCCxACustomEvent *)event2];
        
        OMCCxAPageViewEvent *event3 = [OMCCxAPageViewEvent build:^(id builder) {
            [builder setPageUrl:@"CxaPageUrl"] ;
            [builder setPageTitle:@"CxaPageTitle"];
            [builder setReferrer:@"CxaReferrer"];
        }];
        
         [analytics logEvent: (OMCCxAPageViewEvent *)event3];
        
        
        NSMutableArray *itemArray = [NSMutableArray array];
        
        [itemArray addObject:[OMCCxAEcommerceTransactionItemEvent build:^(id builder) {
            [builder setSku:@"CxaItemSku"];
            [builder setName:@"CxaItemName"];
            [builder setCategory:@"CxaItemCategory"];
            [builder setPrice:0.75F];
            [builder setQuantity:1];
            [builder setCurrency:@"USD"];
            //[builder setItemId:@"id"];
        }]];
        
        OMCCxAEcommerceTransactionEvent *event4 = [OMCCxAEcommerceTransactionEvent build:^(id builder) {
            [builder setOrderId:@"CxaOrderId"];
            [builder setTotalValue:350];
            [builder setAffiliation:@"CxaTranAffiliation"];
            [builder setTaxValue:10];
            [builder setShipping:15];
            [builder setCity:@"Boston"];
            [builder setState:@"Massachusetts"];
            [builder setCountry:@"USA"];
            [builder setCurrency:@"USD"];
            [builder setItems:itemArray];
        }];
        
        [analytics logEvent: (OMCCxAEcommerceTransactionEvent *)event4];    

Cordova

Using cxaAnalytics to set up tracking

cxaAnalytics is used to track any events that you want to monitor and send the data on the recorded events to OMCe.

Since the EasyShopping demo for Cordova uses TypeScript, the tracker is instantiated in a TypeScript file - easy-shopping/src/providers/mcs-service.ts:

  initMCS(): void{
    if(typeof MCSNotificationsCordovaPlugin != 'undefined'){
      MCSNotificationsCordovaPlugin.setLogLevel(mcsConfig.logLevel || this.mcs.LOG_LEVEL.NONE);
    }
    this.mcs.init(mcsConfig);
    this.mcs.cxaAnalytics.setUserId('easy-shopping-demo');
    console.log( "The config has been set and now it has the backend defined in the config as the point of entry for the rest of the functions you need to call.");
  }

Event Tracking

With cxaAnalytics set up, you can define events to be tracked and have occurrences of those events logged.

EasyShopping tracks both standard event types (like screen views and e-commerce transactions) and custom-defined event types.

Let's take a look at some events that are defined in code>easy-shopping/src/providers/cart-service.ts.

  add(product: IProduct) {
    let filtered = this.cart.filter(item => item.id === product.id);
    if(filtered.length === 0){
      let cartProduct = product;
      cartProduct.quantity = 1;
      this.cart.push(cartProduct)
    } else {
      filtered[0].quantity++;
    }
    this.mcsService.logEvent(new this.mcsService.CustomEvent('Cart', 'add', product.id)) 
  }
  ...
    remove(product){
    let idx = this.cart.indexOf(product);
    if(idx > -1){
      this.cart.splice(idx, 1);
    }
    this.mcsService.logEvent(new this.mcsService.CustomEvent('Cart', 'remove', product.id))
  }

  placeOrder(address: any){
    let orderId = '' + new Date().getTime();// unique number
    let total = '' + this.cart.reduce((prev, curr) => prev + (curr.quantity * curr.price), 0);
    let transactionEvent = new this.mcsService.TransactionEvent(
      orderId,          // orderId - Internal unique order id number for this transaction
      total,            // total - Total amount of the transaction
      null,             // affiliation - Partner or store affiliation
      '0',              // tax - Tax amount of the transaction
      '0',              // shipping - Shipping charge for the transaction
      address.city,     // city - City to associate with transaction
      address.state,    // state - State or province to associate with transaction
      address.country,  // country - Country to associate with transaction
      'USD'             // currency - Currency to associate with this transaction
    );

    this.cart.forEach(item => {
      transactionEvent['addItem'](
        item.id,        // sku - Item's SKU code
        item.price.toString(),     // price - Product price
        item.quantity.toString(),  // quantity - Purchase quantity
        item.title,     // name - Product name
        item.depId,     // category - Product category
        'USD',          // currency - Product price currency
      );
    });

    this.mcsService.logEvent(transactionEvent);

    this.cart = [];
  }  

You can find event logging in these classes as well:

  • easy-shopping/src/app/app-component.ts
  • easy-shopping/src/pages/products/products.ts
  • easy-shopping/src/pages/products/tracked-page.ts
  • easy-shopping/src/providers/mcs-service.ts

section 4View logged analytics

  1. Run the app in an emulator or simulator (or on a device), according to the instructions in the sample's README.md file.
  2. In the app, browse the items and create an order or two.
  3. After some time has elapsed, return to the OMCe Analytics instance and click menu icon in the upper left corner of the page and select Analytics > Users.

    In the Events by Event Name tile, you should see a record of the logged events from your session(s) with the app.


more informationWhat's next?

Now that you have a taste for how instrumenting apps for analytics works, you can consult these resources for more details: