Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
LudoNoens
Product and Topic Expert
Product and Topic Expert
38,498
Updated 3 March 2021: added steps to avoid CORS issues on iOS

Updated 5 January 2021: updated as the Neo trial landscape is no longer available

Updated 24 March 2020: added information regarding multiple offline stores

Updated 21 February 2020: as the old Mobile Services sample OData service has been deprecated, I've updated the destination configuration.

 

Important note: although hybrid apps are a valid way to implement offline apps, we strongly recommend using more modern mobile technologies instead. 
When you start developing a new mobile app, we strongly recommend that you consider developing this with either MDK (Mobile Development Kit) for cross platform applications, or our native SDKs (SAP Cloud Platform SDK for iOS or SAP Cloud Platform SDK for Android).

 

A new milestone and a bit of background


As a Product Owner, it is always good to see your product reach a new milestone. Last week, you’ve seen the announcement of Hybrid Application Toolkit release 1805 in Britt’s blog. In this release, we’ve made some fundamental changes in the way we build hybrid apps in the cloud from SAP Web IDE.

It is not my intention to repeat Britt’s blog; but let me just highlight the most important part of this release: Developers have a lot more control on what is packaged into a hybrid app. This opens the door to more possibilities and allows developers to more easily resolve challenges by themselves.

One of the hot topics we did not completely cover in this release is the ability to create offline apps. Many developers have been asking for this. In December 2017, I’ve announced our plans to ‘end-of-maintenance’ the HAT local add-on. We have provided you one offline specific template in SAP Web IDE (with that I mean the Eclipse Orion based version) that could only be used in conjunction with the HAT local add-on. The template is not available in SAP Web IDE Full-Stack. Meanwhile, our colleagues from SAP Web IDE have shut down the old SAP Web IDE and you are advised to migrate projects to the Full-Stack version. So how do you build offline hybrid apps in SAP Web IDE Full-Stack, if we don’t provide the template anymore?

Before answering, let’s look back into the history of this toolkit. When we started, we had no cloud build feature. Instead, we were relying on the locally installed tools for developing Cordova apps. There were templates in Web IDE that kept evolving over time. At some point we’ve decided to grab a snapshot of a UI5 Master Detail template and adapt it to support offline. This template was shipped with HAT, the Web IDE plugin. We then tried to keep up with changes in the original template. At some point, the original template was replaced with a Fiori Master-Detail Application template. We did not further update our offline template, unless really needed.

Although we could have created new mobile specific templates in HAT, we actually wanted the opposite: any template should by default support mobile; hence there should not be mobile variants at all. The functionality we’ve provided last year was actually doing this. When the HAT plugin in Web IDE was active, a newly created project was automatically enabled for mobile. We were adding some magic in the background to make this happen. However, although we’ve tried to make it easier, in reality things got a lot more difficult (especially troubleshooting).

We do not plan to provide you an offline template in SAP Web IDE Full-Stack. The main reason is that every app is unique and requires specific customization around the topic of offline. It is very difficult to provide you this as part of a one-fits-all template. Instead, we will give you guidelines on how to implement offline functionality in your app and provide you with an example below.

Creating an offline app based on the Fiori CRUD Master-Detail template


Prerequisites


Before we start creating the example app, let us first ensure we can access the Mobile Service Sample Service from SAP Web IDE. In your SAP Cloud Platform cockpit, go to Connectivity > Destinations and create a new destination as shown below. Make sure you add the additional properties as indicated. The url is not completely visible is the screenshot. Please enter https://hcpms-<your account number>trial.hanatrial.ondemand.com/mobileservices/origin/hcpms/ESPM.svc/v2. I was using a trial account for this blog post. However, the Neo trial landscape is no longer available. Please adapt the url for your productive environment.



After saving the destination settings, it can take up to a few minutes to have the new destination active.

Update 21/02/2020: for Authentication, please use App2AppSSO.

Now let’s start creating the app from scratch in SAP Web IDE Full-Stack. You can find this version of SAP Web IDE in your SAP Cloud Platform cockpit’s services list:



Although not required at this point, please make sure you have activated Hybrid Application Toolkit. Once you are in SAP Web IDE Full-Stack, go to the preferences and ensure the feature Hybrid App Toolkit is activated. Don't forget to save your selection and reload SAP Web IDE.



You will use the Cloud Build feature based on Mobile Services. Customers who have access a productive environment could see the following in the Hybrid Application Toolkit preferences (depending on your subscription):



If you don't see the Cloud Build Service mentioned in the preference, you will be using Mobile Services by default. If you do see the radio buttons, please ensure the radio button regarding Cloud Build Service is enabled for Mobile Services (not the deprecated one for SAP Fiori).

Creating a new project from a template


In SAP Web IDE, please select File > New > Project from Template. To avoid possible issues with the latest innovation version, I have selected a CRUD Master-Detail template based on SAPUI5 version 1.52. Feel free to use a different version.



In the next step, fill in the details.



In this example I am using the Mobile Service Sample Service to consume OData from a Service URL. We have exposed this service to SAP Web IDE through the destination we have created earlier.



In the Template Customization step, I have selected the following:



Once finished, you can run the application from SAP Web IDE in your web browser. It will show you the data from the data source (read) and you can create new entries (create), change it (update) and remove entries (delete). Also referred to as "CRUD".

Mobile enable the project


Right-click on your project to bring up the context menu and select Mobile > Enable as Hybrid Mobile Project.



This step will add a ‘mobile’ folder to your project, containing some source files only relevant for when your app runs on a device or emulator (as Packaged app, or Developer Companion app).



Take note that during the cloud build process, the contents of the webapp folder and the mobile folder will be merged into the www folder of your Cordova project. The index.html file in the mobile folder will replace the one in your webapp project (if your project has one).

We’ve decided to use this approach, so you can still deploy the webapp to SAP Cloud Platform.

Creating a hybrid app from this project


You can create a Packaged app based on this project by selecting in the context menu: Mobile > Build Packaged App.



In the first step of the build wizard, you can change the app’s name as visible on your device’s home page. You can also select an app icon and images for the splash screen.



In the next step, you indicate for which platform you want to build your app. You'll need to provide a valid the signing profile. For Android devices, you can simply generate one on our service. The provisioning profile for iOS is a bit more tricky. I recommend creating a wildcard App ID on developer.apple.com and include that in the profile which allows you to install the application on your device. Note that this is wildcard App ID is only for development; not for production. You'll then need to export your certificate and provisioning profile and import it here.

Currently, we only have two UI5 versions to select from. We will gradually add more versions.



At this point you can hit the Build button. Once the Cloud Build Service is finished generating your app, a QR code and hyperlink will be displayed, so you can download the app onto your device.



During this build process, Hybrid Application Toolkit will automatically create a new application on Mobile Service, and also create the related Cloud Platform destination for you.

Adding Cordova plugins (optional)


Although not related to the offline topic, I have received several queries on how to add Cordova plugins. So let's quickly discuss this.

In case you want to make use of one or more of the more than 2300 publicly available Cordova plugins in your project, open the context menu and choose Mobile > Select Cordova plugins. You can browse and search for plugins. Once you are done, make sure to save your selection.



When you trigger a new build, the plugins will automatically be added in your Cordova app.

Note that there is a tab called "Default (34)", which does not allow you to make a selection. It merely lists down the plugins we add to your app by default. You'll notice most of the Kapsel plugins are listed there. You don't need to select them. They will be part of your app by default.

Adding the offline capabilities


Before we discuss the offline capabilities, I want to highlight one thing regarding Developer Companion: since this type of app is typically an online app, we cannot use Developer Companion for developing offline apps. Offline will only work for Packaged Apps.

Users who have already created offline apps before using our cloud build service are probably familiar with the way to add the Kapsel Offline OData plugin to the project. This is actually triggered by adding a “sap.mobile” section that defines ‘stores’ in the project’s manifest.json. We have kept this in the new delivery, so that existing projects can more easily transition. The content of this section is actually not important anymore. What matters is that this section is there. Before the HAT 1805 release, the content was used in the build process. As long as you specify the bare minimum, you are fine:
	},
"sap.mobile": {
"definingRequests": {},
"stores": [
]



As a result, your Packaged app built with Cloud Build Service includes the SAP Kapsel Offline OData plugin. Now we need to add some more code to make use of this.

Initializing the offline store


The file mobile/hybrid/sap-mobile-hybrid.js contains most of the bootstrap code for the hybrid app. You are free to make changes here. We are going to add a function to create and open the offline store that will be used to store the data relevant for the app on the device.
    openStore: function() {
console.log("In openStore");
jQuery.sap.require("sap.ui.thirdparty.datajs"); //Required when using SAPUI5 and the Kapsel Offline Store
var properties = {
"name": "store_mainService",
"host": sap.hybrid.kapsel.appContext.registrationContext.serverHost,
"port": sap.hybrid.kapsel.appContext.registrationContext.serverPort,
"https": sap.hybrid.kapsel.appContext.registrationContext.https,
"serviceRoot": fiori_client_appConfig.appID + "_" + mobile_appRoutes[0].destination,

"definingRequests": {
"supplierset": "/Suppliers?$expand=Products"
}
};

store = sap.OData.createOfflineStore(properties);

var openStoreSuccessCallback = function() {
console.log("In openStoreSuccessCallback");
sap.OData.applyHttpClient(); //Offline OData calls can now be made against datajs.
sap.Xhook.disable(); // temporary workaround to ensure the offline app can work in WKWebView
sap.hybrid.startApp();
}

var openStoreErrorCallback = function(error) {
console.log("In openStoreErrorCallback");
alert("An error occurred" + JSON.stringify(error));
}

store.open(openStoreSuccessCallback, openStoreErrorCallback);
},

An important piece to mention here is the serviceRoot specified in the properties. The serviceRoot is basically the location where the offline store will fetch its data, indirectly through Mobile Service. In this particular example I am using the Mobile Service Sample Service; but I could easily change this to use a different destination. The Cloud Platform destination used here was automatically generated by HAT, after triggering the build previously. Also note that the above code assumes one single data source and hence, one single offline store. If your app needs to consume data from multiple sources, you’ll need to open multiple offline stores here.

Updated 19 March 2020: the switch to WKWebView as mentioned in this blog post requires an additional temporary workaround. This is the call to disable Xhook.

In the same file, the appLogon function needs to be adjusted a little bit. Once the logon is done, we call the newly added openStore function, instead of the startApp function.
		if ('serverHost' in context && 'serverPort' in context && 'https' in context) {
// start SCPms logon
sap.hybrid.kapsel.doLogonInit(context, appConfig.appID, sap.hybrid.openStore);

Modification of the datasource uri in the manifest file is no longer required. You can use the same project for running it as online as well as standalone offline app. For existing projects that were mobile enabled, it is advised to remove the 'mobile' folder from the project (you might want to save a copy) and re-enable for mobile. New projects will automatically get the latest code needed when the project is enabled for mobile.

Avoid cross origin (CORS) issues on iOS


With the introduction of iOS 14, the security aspects were further enhanced. To avoid having your application running into cross origin issues, we need to change the settings in the SAP Mobile Services cockpit for Cross Domain Access. This is especially relevant if your app is using the User API (we had a few users facing this).

Please refer to the screenshot below. Please open the SAP BTP Mobile Services Admin Cockpit. Go to Settings -> Security -> Cross Domain Access. Set Origin field to “<AdminAPI>,null”.



Read-only offline app.


Trigger a new cloud build and download your app on your device. After the authentication screen and passcode screen, the screen will go blank for a while. We should actually show something here, so the end-user knows what is happening. This is an improvement to be added later. At this point, the offline store is being synchronised with the backend database. Once this is done, the UI will show up and display the data (this can take around 15 seconds).

You can put your device into airplane mode and continue accessing the data.

Congrats! You’ve built an offline app.

It is nice to be able to Read data when offline, but how about Create, Update and Delete?


The application template is actually already allowing modifications, removal and adding new data entries. But how do we handle this when the device is not connected to the network? The data is simply stored in the on-device offline store. When network connectivity returns, we can synchronise the changes between backend database and on-device store.

To get the latest changes from the backend, we use the refresh function. To upload locally made changes to the backend, we use the flush function.

For the refresh, the most obvious way of implementing this, is as part of the pull-to-refresh. The flush should be triggered once the network connection is back. But for the sake of this demo and making it easier to test, I’ll just add two buttons to the footer bar: a Refresh and a Flush button.

Let’s open the file webapp/view/Master.view.xml and add the following buttons in the customFooterContent.
	<semantic:customFooterContent>
<Button text="Refresh" width="80px" id="__button1" press="onRefreshButton"/>
<Button text="Flush" width="70px" id="__button0" press="onFlushButton"/>
</semantic:customFooterContent>



Now open the file webapp/controller/Master.controller.js and add the following code for handling the button press:
		onRefreshButton: function() {
if (typeof sap.hybrid !== 'undefined') {
sap.hybrid.refreshStore();
}
},

onFlushButton: function() {
if (typeof sap.hybrid !== 'undefined') {
sap.hybrid.flushStore();
}
},

I have added the type check to make sure these calls are only done for a hybrid app. The web app should not call these functions.



We will add the functions called in the file mobile/hybrid/sap-mobile-hybrid.js
	refreshStore: function() {
console.log("Offline events: refreshStore");
if (!store) {
console.log("The store must be open before it can be refreshed");
return;
}
store.refresh(sap.hybrid.refreshStoreCallback, sap.hybrid.errorCallback, null, sap.hybrid.progressCallback);
},

refreshStoreCallback: function() {
console.log("Offline events: refreshStoreCallback");
},

flushStore: function() {
console.log("Offline events: flushStore");
if (!store) {
console.log("The store must be open before it can be flushed");
return;
}
store.flush(sap.hybrid.flushStoreCallback, sap.hybrid.errorCallback, null, sap.hybrid.progressCallback);
},

flushStoreCallback: function() {
console.log("Offline events: flushStoreCallback");
},

errorCallback: function(error) {
console.log("Offline events: errorCallback");
alert("An error occurred: " + JSON.stringify(error));
},

progressCallback: function(progressStatus) {
// console.log("Offline events: progressCallback");

var status = progressStatus.progressState;
var lead = "unknown";
if (status === sap.OfflineStore.ProgressState.STORE_DOWNLOADING) {
lead = "Downloading ";
} else if (status === sap.OfflineStore.ProgressState.REFRESH) {
lead = "Refreshing ";
} else if (status === sap.OfflineStore.ProgressState.FLUSH_REQUEST_QUEUE) {
lead = "Flushing ";
} else if (status === sap.OfflineStore.ProgressState.DONE) {
lead = "Complete ";
} else {
alert("Unknown status in progressCallback");
}
console.log(lead + "Sent: " + progressStatus.bytesSent + " Received: " + progressStatus.bytesRecv + " File Size: " +
progressStatus.fileSize );
},

The refresh and flush functions are asynchronous and will take some time. For demo purposes, I’ve kept the implementation rather simple and added some console logging to have an idea of what is going on. For your enterprise mobile applications, you should implement a way to inform the user about progress and update the UI when needed.

After saving all your code changes, please trigger another cloud build. The result will be an app that allows you to work with your data in online, as well as offline mode. You trigger a refresh to update the on-device store. You can flush the changes made in the on-device store to the data service.

What about data conflicts?


There is one important aspect that I will not discuss in this blog: data conflicts. How do you handle errors when data on the service has changed, while your device was offline, and your user also made changes on the same data?

I think this topic is worth a separate blog post.

Using multiple stores or multiple data sources


Over the past months we have received queries from several users asking about the use of multiple data sources. Customers can have heterogeneous landscapes where data is stored in various systems. When you are building a mobile app that is supposed to work in all kinds of network conditions, you have to use an offline store. Your app might need data from multiple systems. Every data source requires its own offline store. So if you are using data from 'X' number of data sources in your app, you'll need to initialise and open 'X' number of offline stores.

I have seen customers using one single offline store, while their application needs data from multiple sources. To prevent errors in retrieving data, there were various checks in the code to ensure the device was having a network connection. This approach is not recommended. Instead, you should add additional stores. This could require a different way of exposing the data as well.

You might be asking, "Is there a limit to the size or amount of stores ?". The answer simply depends on the amount of storage available on the device. You can have 'N' number of stores, as long as the size of the total storage space required doesn't exceed the storage space on device. The question will be: how much storage space do my target devices have available at a minimum, so my app can work well on all those devices ? In other words and as a practical example: I can have 64GB available on my device, but my colleague has only 2GB free. The answer will be 'less than 2GB' in that case.

In the example code shown above, I've created one 'openStore' function, with a specific serviceRoot and definingRequests, and callback functions for success and failure. You can add more 'openStore' functions where needed. You will also need to implement flush (if required) and refresh functions for each of the stores created. The key will be the serviceRoot and definingRequests. This is where most developers struggle. If the path doesn't match, the initialisation will fail. Please check the troubleshooting section below to resolve this.

Take note that once you add the additional data source to the manifest.json file, the UI5 application will try to fetch metadata from this source when the app initialises; no matter whether there is a network or not; and this could trigger an authentication flow, which you might want to avoid under bad network conditions.

Conclusion


With this blog post I’ve shown you how to create an offline app in SAP Web IDE Full-Stack. The example code provided is very basic. There is surely room for improvement to get this to production level apps. My goal was to show you the basics here, to get you started quickly. I hope this blog post is useful to you and I encourage you to try it out yourself.

Our online documentation is here.

Troubleshooting


After providing support to several users, I'm adding this section to help you in resolving issues you might be facing.

  • You can test the URL used for OData access in the Mobile Service admin cockpit. Select the application and go to Connectivity. Make sure you can Ping the destination. Use the OData application destination test (the icon on the left side of Ping). Specify the relative path as used by your app and click next. You should be able to view data available in the service. If this is not working, then your app will not be able to retrieve data either. Resolve this first before continuing to debug your app.

  • When the offline store is initialised on your device, it will be based on the serviceRoot provided. If you want to make changes to the serviceRoot, you have to delete the existing offline store from your device. Otherwise it will still exist when you restart the app, using the serviceRoot it was initialised with. On iOS, you can remove the store by deleting the app. On Android, removing the app is not sufficient. You also need to clear the app data and cache.

  • A common issue for several users is that the initialisation of the offline store fails. In the example code I am using an alert to indicate this. In case of doubts, you can put a breakpoint on the success callback and error callback to see what is happening.

  • In the file mobile/index.html there is some code to adjust your app's XMLHttpRequests to use URLs that work locally. Please check whether the URL used matches with the serviceRoot you've defined. If the path doesn't match, the app will not use the on-device store.

  • The offline store communicates with Mobile Service over a dedicated channel called Mobilink. You won't be seeing data exchange in the (web) app's logs, as this is handled via native code. Using the Trace functionality in Mobile Service admin cockpit (see Analytics), you will be able to generate a HAR file and get detailed information about the communication between the client app and Mobile Service AND ALSO between Mobile Service and your backend. Check for error messages in the traces to understand why there are failures happening.


Reporting issues


Although I have verified and tested the above flow several times and received confirmation from several users that this works, the results for you might be different. This might be due to interruptions in service availability or changes on the various systems involved. Also take note that I have not tested other scenarios (e.g. on-premise, with Cloud Connector) myself.

For users who are trying to add offline capability to their own app and it fails: please try reproducing exactly the same as described above. Once you have this working, it will be a good reference for your  own application. Adding offline capabilities to a hybrid app is not trivial.

In case you are running into issues, please raise a (BCP) ticket for component CA-WDE-MOB. You can also comment down below, but take note that I will not be monitoring this blog very frequently.

Also, please check my latest blog post "What's new with Hybrid Application Toolkit in 2019" for the latest updates, tips and tricks, ways to resolve issues.

If you found this posting useful, please let me know by hitting the like button.

Thank you!
426 Comments
venkatesh_r_hulekal
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Andre,

I'm stuck with the same issue. It would be great help if you could help me with what you had to change with the model.

 
0 Kudos
Hi Ludo,

 

I am have a problems.

when build package app and install in my phone, this imagen is show.



could you  help me? please.

 
former_member629938
Discoverer
0 Kudos

Hi lnoens

Good Day..!

This Blog is Really Helpful. Thanks for your Quick & Exact Solutions.

Colud you Please Suggest me. how to add Cordova plugin  for native dialer plugin my native/hybrad Mobile app.Plugin also seclected before buld. i don't know how to use/any code need to be keep in our files. Please Guide me.

 

Thanks In Advance

Hari.

 

 

 

LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Hari,

How to use a plugin is not in the scope of Hybrid Application Toolkit. For any public plugin selected through the plugin dialog, please refer to the documentation of the plugin to learn how to use it. This is the same challenge you'll face when building Cordova apps using command line tools.

In general, look for the documentation of the plugin. Sometimes we offer a direct link from the "View Details" option in our dialog. In other cases search for it.

An example of a plugin you could use is cordova-plugin-os-call-number (note: this is a not a recommendation, as I have no idea whether this plugin is suitable for your needs). You can call this using window.plugin.CallNumber.callNumber(onSuccess, onError, number, bypassAppChooser).

Obviously you'll need to add a function that gets called when the 'call' button is pressed.

Regards,
Ludo
tjarliman
Explorer
0 Kudos
Hi Ludo,

If I created FIORI apps using ABAP for FIORI or ABAP Restfull programming, can I create off line apps based on those?

If it can be done, could you pls. share on how to do it? because seems the structure of app project is different in SAP WEB IDE, and it is using different template of project as well.

Thanks in advance.

TJ
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi TJ,

In general, the answer is no. Our tooling does not support ABAP. But you can develop the server side of the application in ABAP. It just won’t run as mobile app. For the front end part, it has to be a UI5 based app, which can be developed as offline mobile app.

You would have think about a separate app for the front end. Don’t try to solve the whole problem in ABAP. Split it into a server side ABAP implementation that provides an OData source, and a UI5 based front end that consumes that OData source. You can also build the mobile apps with our native SDKs or MDK, consuming the same OData source.

Hope this helps.

Ludo

 

 
dominik-st
Participant
Hi Ludo,

I converted a customer project from the old local HAT to a cloud build project.

Opening an and initializing the store works well using the folling code:
var mobile_appRoutes = [{
"path": "/gw_sso",
"manual": true,
"target": {
"type": "destination",
"name": "gw_sso",
"entryPath": "/"
},
"description": "Gateway"
} //...
}

init: function () {
if (sap && sap.hybrid && sap.hybrid.kapsel) {
jQuery.sap.require("sap.ui.thirdparty.datajs"); //Required when using SAPUI5 and the Kapsel Offline Store
this.properties = {
"name": "mainServiceV2",
"host": sap.hybrid.kapsel.appContext.registrationContext.serverHost,
"port": sap.hybrid.kapsel.appContext.registrationContext.serverPort,
"https": sap.hybrid.kapsel.appContext.registrationContext.https,
"serviceRoot": this.serviceUrl, // is: "/gw_sso/sap/opu/odata..
"definingRequests": {
"TourHeaderSet": "/TourHeaderSet?$top=10",
"PlantSet": "/PlantSet",
"ShippingPointSet": "/ShippingPointSet"
}
};

var sAppCID = sap.hybrid.kapsel.appContext.applicationConnectionId;
var sAuth = "Basic " + btoa(sap.hybrid.kapsel.appContext.registrationContext.user + ":" + sap.hybrid.kapsel.appContext.registrationContext
.password);

this.properties["streamParams"] = "custom_header=Authorization:" + sAuth + ";custom_header=X-SMP-APPCID:" + sAppCID + ";";

}

openStore: function () {
console.log("In openStore");
this.store = sap.OData.createOfflineStore(this.properties);
this.store.open(this.openStoreSuccessCallback, this.openStoreErrorCallback);
}

 

But - the offine-store is not used after applying the http-client.

I think the reason is the following coding from OData.js (kapsel-plugin-odata):
var url = request.requestUri;
var requestUrlInfo = getURLInfo(url);

if (requestUrlInfo) {
for (var i = 0; i < openStores.length; i++) {
var storeUrlInfo = getURLInfo(openStores[i].serviceUri);

if (requestUrlInfo.scheme === storeUrlInfo.scheme &&
requestUrlInfo.host === storeUrlInfo.host &&
requestUrlInfo.port === storeUrlInfo.port &&
pathWithSlashes(requestUrlInfo.path).indexOf(pathWithSlashes(storeUrlInfo.path)) === 0)
{
handle = true;
break;
}
}
}

 

The endpoint of the Odata-Model is /destination/servicepath , the endpoint of the offline-store is https://mobile-<account>.hana.ondemand.com/destination/servicepath. So the request ist not handled by the offline-plugin.

I could change the odata service url in the ui5-manifest to the mobile service url, but the app is not hybrid anymore (because the mobile service url cannot be used in the browser).

How can I "force" the app to read the data from the offline store?

 

Best regards

Dominik

 

 

 

 
tjarliman
Explorer
0 Kudos
Ok Got it. Thanks Ludo.
former_member621840
Discoverer
0 Kudos
hie


venkatesh.r.hulekal





please remove after .com/


exp:sap/opu/odata


WebIDESystem = True


 try once .


regard

jai sharma
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Dominik,

Sorry for the late response. I am not monitoring this blog post regularly.

There is some code in the index.html file handling this path. This file can be found in the mobile folder after mobile enablement. If the url used in the request to fetch data doesn't match the url specified during initialisation of the offline store, then the offline store will not be used. You'll probably need to tweak the service root.

Note: once the offline store is initialised, the service root is fixed. You'll have to completely remove the app (and data on Android) to be able to use a different configuration (re-initialise).

Regards,
Ludo
former_member537525
Discoverer
0 Kudos
Hi Ludo,

In the openStore function how we can add more than one serviceRoot?

How we can open multiple offline stores?

Could you give me an example, please?

Thanks and regards,

Krisztian
former_member652152
Discoverer
0 Kudos
Hello Ludo,

I'm have a problem when i try to build APK but cloud build service hasn't finished to build.

Could you give me any solution.

LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Angel,

This behaviour is a bit odd. First of all, could you try the following:

  1. Log out of SAP Web IDE

  2. clear browser cache

  3. Reload SAP Web IDE

  4. Log in

  5. Trigger another build.


If you still encounter the same behaviour, please open the browser developer tools and check the console log and network trace to have some more information on why the creation of the mobile services application fails.

Also, please do not hesitate to raise a support ticket on component CA-WDE-MOB.

Regards,

Ludo
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Krisztian,

It is possible to open multiple offline stores. But you'll have to initialise them individually; not by adding multiple serviceRoots in a single openStore function.

Unfortunately, the example code provided in this blog post does not handle multiple stores and I don't have examples for this. Besides multiple openStore functions, there is other code to be adapted as well to ensure those online service calls are translated/intercepted into local store calls.

Thanks,
Ludo

 
former_member611303
Participant
0 Kudos
Hi


m.chavez_pe,




Please change the following area


cloud platform mobile service ==> nattive/Hybrid == > select the project ==> security


security configuration Basic to SAML 


and check once thank you.


regard


Jai sharma
0 Kudos
Hi Ludo,

You helped me a lot!

Now it works! 🙂

Thanks,

Krisztian
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Krisztian,

Glad to hear ! Did you need to make changes besides the additional openStore function to get it working ?

Thanks,
Ludo
former_member537525
Discoverer
0 Kudos

Hi Ludo,

My short answer is: Yes, I made some small changes.

These were my steps:

  • I removed the mobile folder and added a new oData service to the application.
  • I enabled again the HAT plugin (in this case the HAT will fill the appConfig.js automatically and I don’t have to touch it).
  • In the sap-mobile-hybrid.js file I created 2 different openStore functions (*Note: I commented out the startApp() in the first openStore function).
  • In the second openStore function I renamed the store to store2
  • In the appLogon() I had to call the doLogonInit() twice:
    • sap.hybrid.kapsel.doLogonInit(context, appConfig.appID, sap.hybrid.openStore); 
    • sap.hybrid.kapsel.doLogonInit(context, appConfig.appID, sap.hybrid.openStore2);
  • I created a copy from these functions for the store2:
    • refreshStore, clearStore, closeStoreCallback, flushStore and I renamed the store to store2 in these functions.

Do you know what is the size limitation of the offline store?

How many offline store do we have?

Thanks and regards,

Krisztian

LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Krisztian,

Happy to hear it works for you and good to know it can be done with minimal changes.

I was expecting additional changes in handling the data calls, but it looks like this is not needed.

As for the limits: the only size limit is your device's storage space. For the amount of stores, I think there is no limit either, as long as they fit in the storage space.

Regards,
Ludo
0 Kudos

Hi Ludo,

i’m relativly new to offline hybrid apps , i’ve followed your blog before using web ide trial version and managed to build various hybrid apps.

However now that i’m using web ide full stack version, each time i rey building the packaged app i always get this message :

i have the administrator role for all the mobile services in scp.

If i uncheck and check Android again i get a different error message :

Do you have any suggestion on how to fix this ? thank you! 

LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Rihab,

In both cases, you are using SAP Web IDE Full-Stack. The difference is that on the trial account, some settings were already preconfigured for you. On a production landscape, these settings need to be configured.

You can find the prerequisites here: https://help.sap.com/viewer/8e5c63b6470a4255861c259f3b2d9b41/Cloud/en-US/aa8715ac0a914f12b90fbb88656...

You basically need to go the SAP Cloud Platform cockpit, go to services, find Mobile Services. Select Configure Mobile Services and configure the roles 'Administrator' and 'Notification User'. Select Configure Mobile Services cockpit and configure the role 'HanaMobileAdmin' for your user.

Hope this helps.

Regards,
Ludo
former_member611303
Participant
0 Kudos


Hi krisztian.szabo_hu,





I'm trying but second openStore is not working can you pls share your code here??



thanks .


regard

 jai sharma
former_member666346
Discoverer
0 Kudos

Hello Jai Sharma,

I had to change some sensitive data, but here is the code:

 

/* hybrid capacity bootstrap
*
* This has to happen after sapui5 bootstrap, and before first application page is loaded.
*/

sap.hybrid = {
loadCordova: false,

setCordova: function () {
sap.hybrid.loadCordova = true;
},

packUrl: function (url, route) {
var result;
if (route.manual) { // routes requires a manually created Mobile Destination with Rewrite on Backend and via CP App set
result = route.path; // keep the original path
} else {
var connection = (fiori_client_appConfig.appID + "_" + route.destination).substr(0, 63); // max length cap by SCPms DB
result = "/" + connection;
}
var path = url.substring(route.path.endsWith("/") ? route.path.length - 1 : route.path.length); // the remaining URL path
result += (route.entryPath ? route.entryPath : "") + path;
return result;
},

appLogon: function (appConfig) {
var context = {};
var url = appConfig.fioriURL;
if (url && (url.indexOf("https://") === 0 || url.indexOf("http://") === 0)) {
if (url.indexOf("https://") === 0) {
context.https = true;
url = url.substring("https://".length);
} else {
context.https = false;
url = url.substring("http://".length);
}

if (url.indexOf("?") >= 0) {
url = url.substring(0, url.indexOf("?"));
}
if (url.indexOf("/") >= 0) {
url = url.split("/")[0];
}
if (url.indexOf(":") >= 0) {
context.serverHost = url.split(":")[0];
context.serverPort = url.split(":")[1];
}
}

// set auth element
if (appConfig.auth) {
context.auth = appConfig.auth;
}

// If communicatorId is set then use it to be compatible with existing values. Otherwise, use the default "REST".
// By doing so logon core does not need to send ping request to server root URL, which will cause authentication issue.
// It occurs when the root URL uses a different auth method from the application's endpoint URL, as application can only handle authentication on its own endpoint URL.
context.communicatorId = appConfig.communicatorId ? appConfig.communicatorId : "REST";

// Set disablePasscode to true if you want to hide the passcode screen
context.custom = {
disablePasscode: false
};

if ("serverHost" in context && "serverPort" in context && "https" in context) {
// start SCPms logon
sap.hybrid.kapsel.doLogonInit(context, appConfig.appID, sap.hybrid.openFirstOpenStore);
sap.hybrid.kapsel.doLogonInit(context, appConfig.appID, sap.hybrid.openSecondOpenStore);
} else {
console.error("context data for logon are not complete");
}
},

bootStrap: function () {
if (sap.hybrid.loadCordova) {
// bind to Cordova event
document.addEventListener("deviceready", function () {
// check if app configuration is available
if (fiori_client_appConfig && fiori_client_appConfig.appID && fiori_client_appConfig.fioriURL) {
sap.hybrid.appLogon(fiori_client_appConfig);
} else {
console.error("Can't find app configuration probably due to a missing appConfig.js in the app binary.");
}
}, false);
} else {
console.error("cordova is not loaded");
}
},

loadComponent: function (componentName) {
sap.ui.getCore().attachInit(function () {
// not support sap.ushell navigation
sap.ui.require([
"sap/m/Shell",
"sap/ui/core/ComponentContainer"
], function (Shell, ComponentContainer) {
// initialize the UI component
new Shell({
app: new ComponentContainer({
height: "100%",
name: componentName
})
}).placeAt("content");
});
});
},

openFirstOpenStore: function () {
jQuery.sap.require("sap.ui.thirdparty.datajs"); //Required when using SAPUI5 and the Kapsel Offline Store
var properties = {
"name": "store_first",
"host": sap.hybrid.kapsel.appContext.registrationContext.serverHost,
"port": sap.hybrid.kapsel.appContext.registrationContext.serverPort,
"https": sap.hybrid.kapsel.appContext.registrationContext.https,
"serviceRoot": fiori_client_appConfig.appID + "_" + mobile_appRoutes[0].destination +
"/sap/opu/odata/sap/it_was_our_first_service_url/",

"definingRequests": {
"ItWasOurFirstEntitySet": "/ItWasOurFirstEntitySet"
}
};

store = sap.OData.createOfflineStore(properties);

var openStoreSuccessCallback = function () {
sap.OData.applyHttpClient(); //Offline OData calls can now be made against datajs.
// sap.hybrid.startApp();
};

var openStoreErrorCallback = function (error) {
sap.m.MessageToast.show("An error occurred" + JSON.stringify(error));
};

store.open(openStoreSuccessCallback, openStoreErrorCallback);
},

openSecondOpenStore: function () {
jQuery.sap.require("sap.ui.thirdparty.datajs"); //Required when using SAPUI5 and the Kapsel Offline Store

var properties = {
"name": "store_second",
"host": sap.hybrid.kapsel.appContext.registrationContext.serverHost,
"port": sap.hybrid.kapsel.appContext.registrationContext.serverPort,
"https": sap.hybrid.kapsel.appContext.registrationContext.https,
"serviceRoot": fiori_client_appConfig.appID + "_" + mobile_appRoutes[0].destination +
"/sap/opu/odata/sap/it_was_our_first_service_url/", // we are using the same route from the appRoutes.js file, but it can change!

"definingRequests": {
"ItWasOurSecondEntitySet": "/ItWasOurSecondEntitySet"
}
};
store2 = sap.OData.createOfflineStore(properties);

var openStoreSuccessCallback = function () {
sap.OData.applyHttpClient(); //Offline OData calls can now be made against datajs.
sap.hybrid.startApp();
};

var openStoreErrorCallback = function (error) {
sap.m.MessageToast.show("An error occurred" + JSON.stringify(error));
};

store2.open(openStoreSuccessCallback, openStoreErrorCallback);
},

refreshStore1: function () {
if (!store) {
sap.m.MessageToast.show("The store must be open before it can be refreshed");
return;
}
store.refresh(sap.hybrid.refreshStoreCallback, sap.hybrid.errorCallback, null, sap.hybrid.progressCallback);
},

refreshStore2: function () {
if (!store2) {
sap.m.MessageToast.show("The store must be open before it can be refreshed");
return;
}
store2.refresh(sap.hybrid.refreshStoreCallback, sap.hybrid.errorCallback, null, sap.hybrid.progressCallback);
},

refreshStoreCallback: function () {
sap.m.MessageToast.show("Offline events: refreshStoreCallback");
},

clearStore1: function () {
store.close(sap.hybrid.closeStoreCallback1, sap.hybrid.errorCallback);
},

clearStore2: function () {
store2.close(sap.hybrid.closeStoreCallback2, sap.hybrid.errorCallback);
},

closeStoreCallback1: function () {
store.clear(function () {
sap.m.MessageToast.show("Clear1 Success");
}, sap.hybrid.errorCallback);
},

closeStoreCallback2: function () {
store2.clear(function () {
sap.m.MessageToast.show("Clear2 Success");
}, sap.hybrid.errorCallback);
},

flushStore1: function () {
if (!store) {
sap.m.MessageToast.show("The store must be open before it can be flushed");
return;
}
store.flush(sap.hybrid.flushStoreCallback, sap.hybrid.errorCallback, null, sap.hybrid.progressCallback);
},

flushStore2: function () {
if (!store2) {
sap.m.MessageToast.show("The store must be open before it can be flushed");
return;
}
store2.flush(sap.hybrid.flushStoreCallback, sap.hybrid.errorCallback, null, sap.hybrid.progressCallback);
},

flushStoreCallback: function () {
sap.m.MessageToast.show("Offline events: flushStoreCallback");
},

errorCallback: function (error) {
sap.m.MessageToast.show("An error occurred: " + JSON.stringify(error));
},

progressCallback: function (progressStatus) {
var status = progressStatus.progressState;
var lead = "unknown";
if (status === sap.OfflineStore.ProgressState.STORE_DOWNLOADING) {
lead = "Downloading ";
} else if (status === sap.OfflineStore.ProgressState.REFRESH) {
lead = "Refreshing ";
} else if (status === sap.OfflineStore.ProgressState.FLUSH_REQUEST_QUEUE) {
lead = "Flushing ";
} else if (status === sap.OfflineStore.ProgressState.DONE) {
lead = "Complete ";
} else {
sap.m.MessageToast.show("Unknown status in progressCallback");
}
sap.m.MessageToast.show(lead + "Sent: " + progressStatus.bytesSent + " Received: " + progressStatus.bytesRecv + " File Size: " +
progressStatus.fileSize);
}
};

 

Regards,

Krisztian

former_member611303
Participant
0 Kudos
Hey Krisztian,

Thanks for the quick response it's working but two same screen show in view .

first open store display first service view and

second store display second service view and data is also show in different different view.

can you explain how to hide second view .

thanks

Regards,

jai sharma
former_member666346
Discoverer
0 Kudos

Hello Jai Sharma,

You should start the app once (just in your second open store function):

sap.hybrid.startApp();

You should commented out this line in your first open store function.

Regards,

Krisztian

former_member611303
Participant
0 Kudos
Hey Krisztian,

Yes I commented this line but I have two different services If I'm commented  the first service
sap.hybrid.startApp();

..entity set is not working declare under the first service.

thanks

Regard,

jai sharma
0 Kudos
Hello Ludo,

Thank you for your quick response, i do have all the needed roles and did a retake to check,

I don't get the unauthorized error anymore , however i do still get this error conserning the signing profiles:



thank you,

 
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Rihab,

Can you check the network tab in Chrome DevTools (or other browser) for the GET /ApplicationSigningProfileSet response. Is the response empty?

Regards,
Ludo
0 Kudos
Hello ,

I have followed all the steps given in the blog. Still I am not able to see any offline data . I get the attached error. Online it works fine.Please help.

Thanks and Regards,

Arijit
former_member611303
Participant
0 Kudos
Hey Arijit,

Please send your sap-mobile-hybrid.js code here .

I think you not declare service Root and defining Requests proper.

Thanks

Regard

Jai sharma
former_member666346
Discoverer
0 Kudos
Hello Jai Sharma,

Could you copy here your GET method, please?

Do you have any error code?

Did you try the synchronous read method?

Here is an example:

 
	var sUrl = yournamespace.Component.getMetadata().getManifestEntry("sap.app").dataSources["Z_YOUR_SSERVICE_URL].uri,
oModel = new sap.ui.model.odata.ODataModel(sUrl, true);
oModel.read("YourEntitySet", // Without '/'
null, null,
false,
function (oData) {
// this is the success function
},
function (oData) {
// this is the fail function
var sErrorText = "" + JSON.stringify(oData.responseText.split("\"message\"")[1].split("\"value\"")[1].split("\"innererror\"")[0]);
sErrorText = sErrorText.split(":")[1].split("},")[0];
var sFinalText = sErrorText.substring(2,sErrorText.length-2);
MessageBox.error(sFinalText,
{
styleClass: "sapUiSizeCompact"
}
);
}
);

Regards,

Krisztian
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Krisztian,

I see you are calling the doLoginInit twice, with the callback go to the different openStore functions.

Instead of this, I think it is better to daisy chain the openStore functions. This will open the stores in sequence, and only when both succeed, the app is started.

So at the line where you've commented the startApp, I would call openSecondStore.

Thanks,
Ludo
LudoNoens
Product and Topic Expert
Product and Topic Expert
Indeed, the tricky part is the service Root and defining request. You can test the data retrieval in the SAP Mobile Services cockpit by opening the app configuration and check the connectivity. You should be able to retrieve data using the applied path.

Regards,
Ludo
former_member666346
Discoverer
0 Kudos
Hi Ludo,

Thanks for the suggestion, you are right.

I will rewrite it and the code will look better.

Regards,

Krisztian
former_member668292
Discoverer
0 Kudos
I am getting the following error when I try to add data to the CRUD application.

Can someone please help me with this?

former_member668292
Discoverer
0 Kudos
jai.123 lnoens
former_member611303
Participant
0 Kudos
former_member466137
Participant
0 Kudos
Hello Ludo,

We have licensed cloud account. After activating HAT i don't see option to select Cloud Build Service? Any ideas?

Regards,

Hari
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos
Hi Hari,

Please check the prerequisites in our online help/guide. You will need SAP Mobile Services.

Thanks,

Ludo
former_member611303
Participant
0 Kudos

Hi Ludo ,


When we run the app using webide preview, we get multiple records returned by the odata service, but when we run the app as a hybrid app (after performing Build Packaged App) on the device, we get only single record returned by the service. We had set external break point in the backend and noticed that service is returned multiple records in the output but at the app we get only single record (last record of the result set). Can anyone advice why we are getting different response from oData while running the app as an hybrid app.

Thanks and Regards

Jai Sharma
0 Kudos
Hi Hari,

Please provide link for HAT Download.

 

Regards,

Manojkumar
0 Kudos
Package build failed for ios with the developer certificate. Do we need to mandatorily use the distribution certificate?
0 Kudos
Hi,

 

"Build Packaged App" failed for Android.

I get the following error: "fail to get signing profiles:server returned an invalid response".

when I try to create a signing profile I see the following error:"Mobile services did not return a CSRF token and there is no stored token to use"

 

Can you please advise?

 

Thanks,

Meirav
LudoNoens
Product and Topic Expert
Product and Topic Expert
Hi Meirav,

Can you try: log out of SAP Web IDE and log in again.

Try building again.

Thanks,
Ludo
0 Kudos

Thanks for you reply,

I tried to log out and than back in.

Now I see this error:

Fail to get minimum OS versions: Access unauthorized. Ensure you are assigned to the Administrator role of the correct Mobile Services at the SAP Cloud Platform Cockpit.

And when I try to create profile, I still encounter the same error: “Mobile services did not return a CSRF token and there is no stored token to use”

Thanks,

Meirav

0 Kudos

Hi lnoens ,

 

Thanks for the great blog . May I know how you are debuggin this mobile app?  Remote Debugging Chrome Tools( by turning the developer options in Mobile?) or something else? 

Hi lnoens , krisztian

May I know what is the connection between refreshStore1 , ClearStore1 , refreshStore2 , clearStore2 and when will be  these functions get triggered?
As I can see there is no function is calling these functions. Just wanted to  understand how from the UI refresh store request of second view(second service) hits the refreshStore2 method.
Can you please help me understand this logic.
Thank you very much
0 Kudos

Hello kanganadash

For the debugging:

-You have to enable the developer options in your mobile.

-You have to build the app with debugger mode (in the project settings you should switch to debugging mode from release mode).

-Connent your mobile to the laptop and run the dev remote debugging tool and run the app

For the function triggering:

-You can call these functions in your contollers, with the following command:

Example: sap.hybrid.flushStore2();

Regards,

Krisztian Szabo

LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos

Debugging the mobile app can be done using the standard browsers. For Android apps, you typically connect Chrome devtools. For iOS apps, you connect the tools in the Safari browser on OSX.

The app created in the blog has a refresh button. You could trigger a call to both refreshStore1 and refreshStore2 with this. Or add separate buttons, or implement a pull-to-refresh that triggers the refreshStore relevant for the page you are on. The code in the blog and what I mention here are just examples. It’s up to the developer to implement the user experience here.

The clearStore functions should be called when the user logs out (not implemented in the example here).

Regards,
Ludo

0 Kudos
Hi lnoens ,

 

Thanks for the great blog,

How can we access the logged in user ID from the hybrid mobile app?

below code does not work
if (sap.ushell && sap.ushell.Container) {
this.sUserID = sap.ushell.Container.getService("UserInfo").getId();
}

 

Regards,

Santhosh
LudoNoens
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi Santhosh,

This code will work in the Fiori Launchpad, but not in a packaged mobile app. What you need to do is call the userapi available on SAP Cloud Platform.

https://help.sap.com/viewer/8e5c63b6470a4255861c259f3b2d9b41/Cloud/en-US/2c5d55588c3f4cee839d4084b5a...

Regards,
Ludo