Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
laszlo_kajan2
Active Participant

Foreword


Part 1 of this blog post introduced a barcode scanner hybrid Kapsel app, and covered the details of creating an OData service for it. This part covers the steps needed to create the barcode scanner hybrid Kapsel app from scratch.

The purpose of the example app is to demonstrate that it is possible to couple modern SAP UX technologies to an old 4.7 SAP application server, using an SAP NetWeaver 7.4 gateway system.

Using the camera of a mobile Android device, users can scan a bar code and show the corresponding material from a 4.7 SAP application server. The material scanning app will be launched from a Fiori Launchpad tile. The Fiori Launchpad will be added to the Android home screen as a full screen web app.

The presented app is not a reference. Its purpose is to demonstrate key solutions involved in providing the required functionality.

This blog was made possible by Bertelsmann Media Sp. z o.o. Oddział arvato Polska. Special thanks to Piotr Jakubowski, Andrzej Nowak and Krystian Brydzki for supporting the creation of this blog.

Overview


App development



  1. Material OData service (blog post part 1)

  2. Barcode scanner Kapsel hybrid app (blog post part 2)


Table of contents





Creating the scanner Kapsel hybrid app


Development environment


Install and configure your tool set according to the OpenSAP 'mobile2' course document 'openSAP_mobile2_Week_0_Unit_4_SYDE2_Guide.pdf' [M2W0U4].

Creating a virtual host in the SAP HANA Cloud Connector


Create a virtual host in the HANA Cloud Connector for the gateway system EL6:

  1. Back-end Type: ABAP System

  2. Protocol: HTTP (or HTTPS)

  3. Virtual host and port: 'sapecbox:8060'

  4. Accessible resources, path and all sub-paths:

    1. /api_mgmt_proxy

    2. /plugins/pluginrepository

    3. /sap/bc/adt

    4. /sap/bc/bsp

    5. /sap/bc/ui5_ui5

    6. /sap/opu/odata

    7. /sap/public



  5. Perform the internal host availability check


Creating an HCP destination for the OData service


Create a HANA Cloud Platform (HCP) destination for the ZTUT00_MAT_00_SRV OData service on 'sapecbox:8060':

  1. Open your HANA Cloud Platform (HCP) trial account

  2. Open 'Connectivity / Cloud Connectors' and make sure it is 'Connected'

  3. Open 'Destinations', create a new destination:

    1. Name: 'sapecbox-8060'

    2. Type: HTTP

    3. URL: http://sapecbox:8060/

    4. Proxy Type: OnPremise

    5. Authentication: BasicAuthentication

    6. User: <your_test_user_on_EC6> e.g. FIORDEMO

    7. Password: <password_of_FIORDEMO>

    8. Additional Properties:

      1. sap-client: <client_on_EC6> e.g. 505

      2. WebIDEEnabled: true

      3. WebIDESystem: EL6

      4. WebIDEUsage: odata_abap,odata_gen,ui5_execute_abap,dev_abap,bsp_execute_abap,plugin_repository





  4. Perform the destination availability check

    • Occasionally it may be necessary to perform the test quite a few times until it becomes successful (green)




Displaying the material list and material details


Creating the barcode scanner hybrid Kapsel app


Create a hybrid Kapsel app to display materials using the OData service ZTUT00_MAT_00_SRV:

  1. Open your HANA Cloud Platform (HCP) trial account

  2. Open the SAP Web IDE service

  3. Go to 'Preferences / Plugins', enable the 'Hybrid App Toolkit' (HAT) plugin

    1. Test the connection and make sure the Web IDE can connect to your local HAT installation



  4. Create a new project from the template 'SAPUI5 Master Detail Kapsel Application'

    1. Project name: <your>.<fqdn>.tut00mat00, e.g. 'pl.arvato.tut00mat00'

    2. Sources: 'Service Catalog', choose the destination added above, e.g. 'sapecbox-8060', choose the service 'ZTUT00_MAT_00_SRV', then 'Next'

    3. Project Namespace: <your>.<fqdn>.tut00mat00, e.g. 'pl.arvato.tut00mat00'

    4. Master Section

      1. Title: Material List

      2. OData Collection: MaterialSet

      3. Search Placeholder: MatNr

      4. Search Tooltip: Material number

      5. Search Field: MatNr



    5. Main Data Fields:

      1. Item Title: MatNr

      2. Numeric Attribute: GrossWt

      3. Units Attribute: UnitOfWt



    6. Detail Section:

      1. Title: Material Details

      2. Additional Attribute 1: MatlDesc



    7. Click 'Next', 'Finish'



  5. Fix a bug in the new project that comes from the template:

    1. Edit 'view/Master.controller.js', replace all 'sProductPath' with 'sEntityPath'. In onDetailChanged(), the oData parameter has no 'sProductPath' property. The property is 'sEntityPath'.




Running the barcode scanner app in Chrome



  1. Highlight the new project 'pl.arvato.tut00mat00'

  2. Click the green 'Run' icon on the toolbar

    • The app is started in a new Chrome tab

    • The app displays a list of materials. Choosing a material brings up its details.




Initializing the local git repository of the project



  1. Go to your HCP account / Repositories / Git Repositories

  2. Create a new repository

    1. Repository Name: tut00mat00

    2. Description: pl.arvato.tut00mat00 barcode scanned hybrid Kapsel app

    3. OK

    4. Click on the new repository and copy its 'Git Repository URL' to the clipboard



  3. Go to the Web IDE

  4. Right click the project 'pl.arvato.tut00mat00', choose Git / Initialize Local Repository

    1. Paste the copied URL to the URL field, optionally adding your user name, e.g. 'https://username@...'

    2. OK



  5. Open the 'Git Pane' from the right side of the Web IDE

    1. Perform a 'Pull'

    2. Click 'Stage All'

    3. Fill in 'Commit Description': 'Initial import'

    4. Click 'Commit and Push / Remote Branch'

      1. Choose 'origin/master', OK






Deploying the barcode scanner app on an Android device



  1. Set the Cordova Android version for your local HAT to at least '5.1.0':

    1. Edit your local '<HAT_installation>/config.json', set "platforms"."android"."version" to "5.1.0"



  2. Connect your Android device (or start an emulator)

  3. Make sure the Android debugger sees the device:

    1. command_line$ adb devices



  4. In Web IDE, right click the project, choose 'Project Settings / Device Configuration'

    1. Application

      1. App name: 'My First Material Scanner App'

      2. App id: 'pl.arvato.mat00tut00'

      3. Description: 'Scan a barcode to display material details'



    2. Build Options

      1. 'Debug Mode' - to allow app debugging from Chrome



    3. Platforms

      1. Check 'Android'



    4. Plugins

      1. Kapsel

        1. The app, when deployed on a mobile device, will use HTTPS to access the OData service. In order to handle user authentication, use the Kapsel 'Logon Manager' plugin:

          1. Check 'Logon Manager'

          2. Set the 'HCPms Host' to 'noserver.ondemand.com', since the HANA Cloud Platform mobile services will not be used here

          3. Edit 'dev/devlogon.js' 'doLogonInit' function, change 'if (window.sap_webide_companion) {' to
            if (window.sap_webide_companion || context.serverHost === "noserver.ondemand.com") {






      2. Custom

        1. Instead of the relatively old Kapsel 'Barcode Scanner' plugin, use the custom 'phonegap-plugin-barcodescanner' plugin:

          1. Add or Remove / 'phonegap-plugin-barcodescanner', '+'

          2. OK







    5. Preferences

      1. Android

        1. Set 'URI Scheme' to 'pl.arvato.tut00mat00', for Android/Chrome intent navigation 'pl.arvato.tut00mat00:///'





    6. Save the device configuration

    7. Set the externalURL of the OData service:

      1. Edit '.project.json', add after "hcpmsServer":
        "externalURL": "http[s]://<URL_of_gateway>:<port>/sap/opu/odata/sap/ZTUT00_MAT_00_SRV",






  5. Right click the project, Run / Run On / Android Device

    1. Wait for the build to complete

    2. The app will start on your mobile device, and will probably ask for a user name and password as part of the HTTP 'basic authentication'

      • In case you want to use client certificate authentication [CLCRT]:

        1. Edit 'hybrid/config.xml', add into the '<widget>' section:
          <platform name="android">
          <preference name="SAPKapselHandleHttpRequests" value="true" />
          </platform>


          • Note: you will have to reapply this change after each deployment from the Web IDE



        2. cd hybrid

        3. cordova run android --device





    3. The app should display the same list of materials and material details as before, when it was run in Chrome




Adding the scanner button


Currently the user can display material details by selecting an item on the 'Material List' screen, but can not scan a barcode. Add a button to show material details corresponding to a scanned barcode:

  1. Open the 'Master.view.xml' of the app in the text editor of the Web IDE

  2. Add the scanner button 'sap.ndc.BarcodeScannerButton' [BCSCR] to the top right content area, into '<Bar id="searchBar">':
    <contentRight>
    <ndc:BarcodeScannerButton scanSuccess="handleBarcodeScannerSuccess" />
    </contentRight>


  3. Add namespace 'xmlns:ndc="sap.ndc"' to the view: '<mvc:View ... xmlns:ndc="sap.ndc" ...>'

  4. Add a new event handler method 'handleBarcodeScannerSuccess' to 'Master.controller.js':
         handleBarcodeScannerSuccess: function(event) {

    //console.log("handleBarcodeScannerSuccess " + JSON.stringify(event.mParameters));

    if(!event.mParameters.cancelled){

    // Make sure you update the path below to your formatter function:
    var sEntityPath = pl.arvato.tut00mat00.util.Formatter.encodeMaterialSetMatNr(event.mParameters.text);
    var bReplace = jQuery.device.is.phone ? false : true;

    this.showDetailForPath(sEntityPath, bReplace);
    }
    }


  5. Use the router's hash navigation [HNAV] to display the detail page of the scanned material. Add to 'Master.controller.js':
         showDetailForPath: function(path, bReplace) {

    this.getRouter().navTo("detail", {
    from: "master",
    entity: path,
    tab: this.sTab
    }, bReplace);
    },


  6. Add a formatter method to 'util/Formatter.js':
         encodeMaterialSetMatNr: function(matNr){

    var newMatNr = encodeURIComponent(matNr).replace(/'/g, "%27");
    var sEntityPath = "MaterialSet('" + newMatNr + "')";

    return sEntityPath;
    }


  7. Test the application in Chrome (in case you have a camera)

    1. Scan a valid bar code: the app will navigate to the corresponding detail view

    2. Scan an invalid bar code: 'Not Found / The requested resource was not found' is shown




Importing the Kapsel project to Android Studio


Certain device specific development can be performed much more easily in Android Studio than in the Web IDE, because of the shorter time it takes to test changes. In this case, 'git' is needed to keep track of, and synchronize changes introduced in Android studio or the Web IDE. Unfortunately this development methodology is currently not well supported. In particular, the local git working copy established in '<tut00mat00_project>/hybrid/platforms/android/assets/www' is destroyed after each redeployment from the Web IDE.

  1. Go to the Web IDE

    1. Edit 'dev/devapp.js' 'onDeviceReady' function, change '$.getJSON(".project.json", function(data) {' to
      $.getJSON((window.cordova ? "project.json" : ".project.json"), function(data) {


    2. Edit '.gitignore' and add:
      cordova-js-src
      cordova.js
      cordova_plugins.js
      plugins
      resources
      smp


    3. Commit and push all your changes to git



  2. Use your favorite git client to clone the git repository to a temporary location on your desktop computer

    1. Create and check out a new branch 'platforms/android' for the local copy

    2. Push the new branch back to the HCP 'origin'

    3. Copy '.git' of the temporary working copy to '<tut00mat00_project>/hybrid/platforms/android/assets/www'

      • Note: you will have to reapply this change after each deployment from the Web IDE



    4. Stage and commit changes to 'index.html' and 'project.json'

    5. Discard local changes to all other files if any



  3. For faster 'gradle' builds, create the file '<tut00mat00_project>/hybrid/platforms/android/gradle.properties' in the locally deployed project, with this content: 'org.gradle.jvmargs=-Xmx2048M'

    • Note: you will have to reapply this change after each deployment from the Web IDE



  4. Start Android Studio

    1. Import Project / '<tut00mat00_project>/hybrid/platforms/android'

      • Note: you will have to reapply this change after each deployment from the Web IDE



    2. Keep the 'gradle' version (recommended) - or -

      1. Allow Android Studio to update gradle to a newer version, click 'Fix Gradle wrapper and re-import project' if it appears



    3. Wait for the initial Gradle build to complete

    4. Choose 'Run' menu / Run 'android' / Choose an Android device

    5. Test the scanner button on valid, and invalid bar codes




Launching the scanner hybrid Kapsel app from a Launchpad tile



  1. Open the Fiori Launchpad Designer

    1. Create a new tile in the catalog of your choice with semantic navigation, to semantic object 'Material', action 'tut00mat00'

    2. Create a target mapping for 'Material' 'tut00mat00':

      1. Application Type: 'URL'

      2. URL: 'pl.arvato.tut00mat00:///'

      3. 'Device Types': uncheck 'Desktop' (optional)





  2. Open the Fiori Launchpad on the mobile device in Chrome

    1. Launch the app by touching the new tile




Handling Android lifecycle events


In case your Android test device has sufficient amount of RAM, the scanner app has most likely worked correctly so far. However, in case of RAM shortage, Android may kill the app while performing the scanning activity, and restart the app afterwards. This is normal behavior [ALG], that will certainly happen occasionally. In order to test the behavior of the scanner app under low memory conditions, enable 'Settings / Developer options / Don't keep activities'. This forces the app to be destroyed before, and recreated after each time it is put into the background. This means when performing a scanning or simply returning to the Home screen.

  1. Enable 'Settings/Developer options/Don't keep activities'

  2. Run the app

    1. Navigate to the details of a material

    2. Hit the home (circle) button

    3. Return to the app: note that the app no longer shows the previous material details. It has been restarted.

    4. Run the app again and perform a scanning. The app shows its initial state, instead of the details of the scanned item.




Returning to the last material detail screen when the app is resumed


Events 'pause' and 'resume' can be used to react to Android lifecycle events. The 'resume' event handler has to be set as early as possible, so before the component's init() is called.

  1. Store the material whose details are being shown on 'pause':

    1. Edit index.html, add after '<link rel="stylesheet" type="text/css" href="css/style.css">':
      <script>
      var APP_STORAGE_KEY = "pl.arvato.tut00mat00.appState";
      var appState = { hash: null };
      </script>


    2. Edit Component.js 'init:', add after 'this.setModel(i18nModel, "i18n");':
      // Bind lifecycle events
      this.bindPauseEvent();


    3. Edit new methods to the component:
      bindPauseEvent: function(){

      var that = this;
      document.addEventListener("pause", function() {
      that.handlePause.apply(that, arguments);
      }, false);
      },

      handlePause: function(event){

      // Save hash so we can return to it on resume
      appState.hash = sap.ui.core.routing.HashChanger.getInstance().getHash() || "";

      window.localStorage.setItem(APP_STORAGE_KEY, JSON.stringify(appState));
      },




  2. Retrieve and show the last material upon 'resume':

    1. Edit index.html:

      1. Add after 'jQuery.sap.require("pl.arvato.tut00mat00.dev.devapp");':
        jQuery.sap.require("pl.arvato.tut00mat00.util.earlyResume");


      2. Add after 'window.onload = function() {':
        pl.arvato.tut00mat00.util.earlyResume.bindEvent();




    2. Create 'util/earlyResume.js':
      jQuery.sap.declare("pl.arvato.tut00mat00.util.earlyResume");

      pl.arvato.tut00mat00.util.earlyResume = {

      bindEvent: function(){

      document.addEventListener("resume", function() {
      pl.arvato.tut00mat00.util.earlyResume.handleEarlyResume.apply(null, arguments);
      }, false);
      },

      handleEarlyResume: function(){

      if(appState.hash === null){ // No previous state, restore from localStorage

      var appStateJSON = window.localStorage.getItem(APP_STORAGE_KEY);

      if(appStateJSON && appStateJSON !== "null"){

      appState = JSON.parse(appStateJSON);

      if(appState.hash){

      // There is no sap.ui.core.routing.HashChanger yet. Defer the below till later, when there is:
      appState.controllerParentInitDeferred = jQuery.Deferred();

      jQuery.when(appState.controllerParentInitDeferred).then(function() {

      delete appState.controllerParentInitDeferred;

      sap.ui.core.routing.HashChanger.getInstance().setHash(appState.hash);
      });
      }
      }
      }
      }
      };


    3. Edit 'Component.js', add to 'init' after 'sap.ui.core.UIComponent.prototype.init.apply(this, arguments);':
      // Resolve deferred object of resume
      if(typeof appState !== 'undefined' && appState.controllerParentInitDeferred){ appState.controllerParentInitDeferred.resolve(); }




  3. Run the app and test:

    1. Choose a material to display its details

    2. Go to the Home screen (circle button)

    3. Return to the app

      • The app is restarted and returns to the last material displayed






Displaying the scanned material when the app is resumed


Handle the 'resume' event that carries the result of the scanner plugin:

  1. Edit 'Component.js', add to the top:
    jQuery.sap.require("pl.arvato.tut00mat00.util.Formatter");


  2. Edit 'util/earlyResume.js'

    1. Add after 'if(appState.hash === null){':
      // Handle pending plugin results if any
      if (event && event.pendingResult && event.pendingResult.pluginServiceName &&
      event.pendingResult.pluginServiceName === "BarcodeScanner" &&
      event.pendingResult.pluginStatus === "OK" && !event.pendingResult.result.cancelled) {

      pl.arvato.tut00mat00.util.earlyResume.handleBarcodeScannerPendingResult(event);
      return;
      }


    2. Add a new method:
      handleBarcodeScannerPendingResult: function(event){

      //console.log("resume registering scanner deferred: " + JSON.stringify(event));
      appState.controllerParentInitDeferred = jQuery.Deferred();

      jQuery.when(appState.controllerParentInitDeferred).then(function() {

      delete appState.controllerParentInitDeferred;

      // Set URL hash e.g. #/MaterialSet('MatNr%201') and start with that
      var sEntityPath = pl.arvato.tut00mat00.util.Formatter.encodeMaterialSetMatNr(event.pendingResult.result.text);

      //console.log("resume early deferred: about to set hash to " + sEntityPath);
      sap.ui.core.routing.HashChanger.getInstance().setHash(sEntityPath);
      });
      }




  3. The current version (6.0.1) of the barcode scanner plugin 'phonegap-plugin-barcodescanner' does not handle application resume, hence its result is lost. A simple patch fixes this:

    1. Edit (in e.g. Android Studio) 'android / java / com.phonegap.plugins.barcodescanner / BarcodeScanner.java' and override 'onRestoreStateForActivityResult' of the BarcodeScanner class:
      @Override
      public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) {
      this.callbackContext = callbackContext;
      }


    2. Add the corresponding import:
      import android.os.Bundle;




  4. Run and test the app

    • After scanning, the details of the scanned material are shown



  5. Disable 'Settings / Developer options / Don't keep activities'


Do not forget to commit your changes to the git repository.

Adding the Fiori Launchpad to the Android Home screen as a web app


Make the Fiori Launchpad open like a native Android app [WAPP], by adding it to the Home screen:

  1. Create the Android web app 'manifest.json' file on your local machine:
    {
    "name": "Tutorial Launchpad",
    "description" : "Tutorial Launchpad - Start Here",
    "start_url": "/sap/bc/ui5_ui5/sap/ztut00ushell00/shells/abap/FioriLaunchpad.html",
    "display": "standalone",
    "orientation": "any",
    "background_color": "white"
    }


  2. Start the ABAP Development Workbench (SE80)

    1. Make a copy of the BSP project '/UI2/USHELL' to 'ZTUT00USHELL00'

    2. Edit the new 'shells/abap/FioriLaunchpad.html' and add before '<!-- iPhone splash screens -->':
      <!-- Android web app -->
      <!-- https://developer.chrome.com/multidevice/android/installtohomescreen -->
      <link rel="manifest" href="https://blogs.sap.com/sap/bc/bsp/sap/ztut00ushell00/manifest.json" />


    3. Import 'manifest.json' as a new MIME object 'manifest.json':

      1. Mime Type: 'application/manifest+json'



    4. Activate the BSP project



  3. Create a new ICF node

    1. SICF / /default_host/sap/bc/ui5_ui5/sap/ / New Sub-Element

    2. Name of Service: 'ztut00ushell00'

    3. Save the new service and go back to the 'Maintain service' view

    4. Activate the 'ztut00ushell00' service



  4. Test the new launchpad

    1. Navigate to 'https://<yourgw>:<port>/sap/bc/ui5_ui5/sap/ztut00ushell00/shells/abap/FioriLaunchpad.html'

    2. Test the manifest file by opening 'https://<yourgw>:<port>/sap/bc/bsp/sap/ztut00ushell00/manifest.json'



  5. Add the new launchpad to the Android Home screen

    1. Navigate to the new launchpad in Chrome on the mobile device

    2. Choose 'Add to Home screen'



  6. Launch the app from the Android Home screen

    1. The app is launched in full screen mode




This concludes the tutorial.

Further reading


[M2W0U4] openSAP mobile2 / Setting Up Your Development Environment

[CLCRT] Getting Started with Kapsel - Part 8 -- AuthProxy

[BCSCR] SAPUI5 SDK - Demo Kit / sap.ndc.BarcodeScannerButton

[HNAV] Navigation - UI Development Toolkit for HTML5 (SAPUI5) - SAP Library

[ALG] Android Platform Guide - Apache Cordova - Lifecycle Guide

[WAPP] Add web app to Homescreen - Google Chrome

Afterword to this blog post


Thank you for reading this blog post. I hope you found it useful.
1 Comment
Labels in this area