Search code examples
androidibm-mobilefirstcordova-plugins

Fire javascript event listener from native Android code using Worklight


I'm reading the following tutorial: https://www.ibm.com/developerworks/community/blogs/worklight/entry/android_combining_native_and_web_controls_in_cordova_based_applications?lang=en.

I'm trying to follow the tutorial and integrate it in my app with ReactJS. I created a plugin to call native and javascript code, my Cordova plugin is in HybirdBridge.java and my javascript listener is in NativeEventListener.js. My code can be found here: https://github.com/nguyengiangdev/HybridBridge

I have a search button in the action bar. When I click the search button I try to invoke the javascript event but it throws a Null Pointer Exception in the listenerCallbackContext.

I don't know why? Can anyone help me with this?

Thanks


Solution

  • You should check the MobileFirst Platform (formerly known as Worklight) Developer Center for more information on this topic.

    The following link has various tutorials for Android, iOS and Windows Phone on how to add native functionality to hybrid applications.

    https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-0/adding-native-functionality/

    Starting with Worklight 6.2 you can pass data back and forth between hybrid and native without creating your own Cordova plugin by using the following code:

    Hybrid to Native

    Send

    var data = { someproperty : 1234 };
    WL.App.sendActionToNative("doSomething", data);
    

    Hybrid to Native

    Receive

    WL.getInstance().addActionReceiver(new WLActionReceiver() {
        void onActionReceived(String action, JSONObject data){
          // process received action
        }
    });
    

    Native to Hybrid

    Send

    JSONObject data = new JSONObject();
    data.put("someProperty", 12345);
    WL.getInstance().sendActionToJS("doSomething", data);
    

    Receive

    WL.App.addActionReceiver ("MyActionReceiverId", function(received) {
        if (received.action === "doSomething"){ 
            // handle the data received
        }
    });
    

    For more information about this visit: http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.0.0/com.ibm.worklight.dev.doc/devref/t_sending_actions_native_to_js.html

    Other useful links:

    Getting Started with IBM MobileFirst Platform:

    https://developer.ibm.com/mobilefirstplatform/documentation/getting-started/

    IBM MobileFirst Platform Foundation v7 Knowledge Center:

    http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.0.0/wl_welcome.html