I am trying to reproduce a very simple example from Apache Cordova’s Plugin Development Guide. The sample HTML JavaScript does not seem to be executing beyond the call to the Android Java Plug in. Here is the Java Code that deploys to the Android Emulator successfully and opens index.html:
MainActivity.java
package com.essentialsoftware.testbump;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import org.apache.cordova.*;
public class MainActivity extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
}
Here is the java plugin:
Echo.java
package com.essentialsoftware.testbump;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class echoes a string called from JavaScript.
*/
public class Echo extends Plugin {
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
try {
if (action.equals("echo")) {
String echo = args.getString(0);
if (echo != null && echo.length() > 0) {
return new PluginResult(PluginResult.Status.OK, echo);
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
} else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
}
Here is the web page that invokes Echo:
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<script src="cordova-2.0.0.js"></script>
</head>
<body>
<h1 id="demo">Hello World</h1>
<script type="text/javascript">
document.getElementById("demo").innerHTML="Before function declaration";
window.echo = function(str, callback) {
cordova.exec(callback, function(err) {
callback('Nothing to echo.');
}, "Echo", "echo", [str]);
};
document.getElementById("demo").innerHTML="After function declaration";
window.echo("echome", function(echoValue) {
alert(echoValue == "echome"); // should alert true.
});
document.getElementById("demo").innerHTML="After function invocation";
alert("hello" == "Goodbye");
document.getElementById("demo").innerHTML="Test2";
</script>
</body>
</html>
When index.html opens in the android emulator it displays:
After function declaration
If I am correct, this means the JavaScript is erroring out in
window.echo("echome", function(echoValue) {
alert(echoValue == "echome"); // should alert true.
});
Any advice as to what I am doing wrong? Any tips for debugging the JavaScript or my Andriod Java Code?