Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ScriptEngineManager in Android?

import android.widget.Toast;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

 public void bEqual(View v) throws ScriptException {

       ScriptEngineManager mgr = new ScriptEngineManager();
       ScriptEngine engine = mgr.getEngineByName("JavaScript");
        String value = inputText.getText().toString();
        Toast.makeText(this,value,Toast.LENGTH_LONG).show();
        try{
            result = (double)engine.eval(value);
            Toast.makeText(this,String.format("%f",result),Toast.LENGTH_SHORT).show();
        }catch(Exception e){
            Toast.makeText(this,"Exception Raised",Toast.LENGTH_SHORT).show();
        }

    }

What is wrong in it? App is exiting when perform this action. It is not showing any errors but app is closing

like image 359
rrkjonnapalli Avatar asked Dec 19 '22 09:12

rrkjonnapalli


1 Answers

Easiest way is to use Mozilla Rhino in Android instead[1] because ScriptEngine and it's dependencies would require time consuming setup and headache.

Import the ff:

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import android.util.Log;

Code you put somewhere in your method:

    Context context = Context.enter(); // 
    context.setOptimizationLevel(-1); // this is required[2]
    Scriptable scope = context.initStandardObjects();
    Object result = context.evaluateString(scope, "18 > 17 and 18 < 100", "<cmd>", 1, null);
    Log.d("your-tag-here", "" + result);

Add it in your gradle dependencies.

implementation group: 'org.mozilla', name: 'rhino', version: '1.7.10'

Reference:

  1. Mozilla Rhino
  2. Explanation why that line of code is needed
  3. Mozilla Rhino's Maven Repository
like image 135
Miko Chu Avatar answered Jan 05 '23 00:01

Miko Chu