Search code examples
androidibm-mobilefirstjson

Android: MobileFirst sending data from Native to cross page


My Task is as follows: using IBM MobileFirst create a Hybrid app and implement a JS calculator. show date retrieved from native java APIs to the web page.

My attempts:

  1. I followed Documentations here and implemented the whole Native code onCreate method
  2. I found this answer"the first one" illustrating that i should use it on onInitWebFrameworkComplete,

    • Solution provided didn't work
    • I am working with MobileFirst version 7
    • full sample code is provided

Suggestion: should i create the whole action bar in native code then merge it in the cross ui, is that available? I only need to send a petite string of date


Solution

  • I am not clear on your attempts, so here is a quick demonstration how to click a button in HTML and trigger the Send Action API to get the current Date in Java and return it to JavaScript, and then display it.

    index.html

    <button onclick="getDateFromJava();">show current date from Java</button>
    

    main.js

    function wlCommonInit(){
        WL.App.addActionReceiver ("returneDdateFromJava", returnedDateFromJava);
    }
    
    function getDateFromJava() {
        WL.App.sendActionToNative("retrieveDate");
    }
    
    function returnedDateFromJava(received){
        if (received.action === "returnedDateFromJava"){ 
            alert (JSON.stringify(received));
        }
    }
    

    main Java class file

    1. Find onInitWebFrameworkComplete
    2. Add an ActionReceiver after the else:

      import com.worklight.androidgap.api.WLActionReceiver;
      ...
      ...
      
      public void onInitWebFrameworkComplete(WLInitWebFrameworkResult result){
          if (result.getStatusCode() == WLInitWebFrameworkResult.SUCCESS) {
              super.loadUrl(WL.getInstance().getMainHtmlFilePath());
          } else {
              handleWebFrameworkInitFailure(result);
          }
      
          ActionReceiver ActionReceiver = new ActionReceiver();
          WL.getInstance().addActionReceiver(ActionReceiver);
      }
      

    ActionReceiver class

    package com.getDateApp;
    
    import java.util.Date;
    import org.json.JSONException;
    import org.json.JSONObject;
    import com.worklight.androidgap.api.WL;
    import com.worklight.androidgap.api.WLActionReceiver;
    
    public class ActionReceiver implements WLActionReceiver{
        public void onActionReceived(String action, JSONObject data){
            if (action.equals("retrieveDate")){
                Date date = new Date();
    
                JSONObject returnedDate = new JSONObject();
                try {
                    returnedDate.put("dateFromJava", date);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                WL.getInstance().sendActionToJS("returnedDateFromJava", returnedDate);
            }
        }
    }