Shortest Code for a Simple Calculator on Android

String RESULT;
String input = "(1+3)/4 * 2 - 7";
...
webSettings.setJavaScriptEnabled(true);
...
webView.addJavascriptInterface(new JavaScriptInterface() {
   public void returnResult(String o) {
       RESULT = o;
   }}, "JavaCallback"));
webView.loadUrl("javascript:window.JavaCallback"
   + ".returnResult("+input+")");
// now RESULT is -5

Is there a shorter one? BTW: this is only a sketch not sure if I miss a bracket somewhere …

2 thoughts on “Shortest Code for a Simple Calculator on Android

  1. Tried it and it doesn’t work:

    public interface TermResultListener {
    public void returnResult(String result);
    }

    public static void calculateTermResult(Context context, String inputTerm,
    TermResultListener resultListener) {
    WebView webView = new WebView(context);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(resultListener, “JavaCallback”);
    webView.loadUrl(“javascript:window.JavaCallback” + “.returnResult(”
    + inputTerm + “)”);
    }

  2. You’ll need to display the webView – probably there are hacks to avoid it. so, either put it in your layout or add it to the activity programmatically.

Comments are closed.