I cant figure out how to get data back from JAVA to javascript so I can update the UI using Cordova on Android. here are two buttons, as they are pressed they increment the position counter which I want to return to the UI and update the screen but cannot figure out how its returned.
I thought I could just add the switchPos to the callback but cant seem to pick it up anywhere in javascript, I was planning to write the value to the UI with a ".innerHTML =" statement.
Here is the plugin javascript.
cordova.define(‘myplugin', function (require, exports, module) {
module.exports = {
switch1: function (success, failure) {
cordova.exec(success, failure, “MyPlugin", “switch1”, []);
},
switch2: function (success, failure) {
cordova.exec(success, failure, “MyPlugin", “switch2”, []);
}
};
});
Here is the javascript that calls them.
var myplugin = cordova.require('myplugin');
var myapp = {
appButton1: function(){
myplugin.switch1();
},
appButton2: function(){
myplugin.switch2();
}
};
Here is the JAVA code for the plugin.
public class MyPlugin extends CordovaPlugin {
// actions
private static final String SWITCH1 = “switch”1;
private static final String SWITCH2 = “switch”2;
// callbacks
private CallbackContext connectCallback;
// Switch Counters
public static int switchPos1 = 1;
public static int switchPos2 = 1;
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
boolean validAction = true;
if (action.equals(SWITCH1)) {
Log.d("Valid Action = SWITCH1 Pos: “ + switchPos1);
switchPos1++;
callbackContext.success(switchPos1);
} else if (action.equals(SWITCH2)) {
Log.d("Valid Action = SWITCH2 Pos: “ + switchPos2);
switchPos2++;
callbackContext.success(switchPos2);
} else {
validAction = false;
}
return validAction;
}
}
when you call the plugin you have to pass the success and failure functions:
var myplugin = cordova.require('myplugin');
var myapp = {
appButton1: function(){
myplugin.switch1(function(data){alert(data);},function(error){alert(error);});
},
appButton2: function(){
myplugin.switch2(function(data){alert(data);},function(error){alert(error);});
}
};