How to use ScriptEngineManager in Android?

rrkjonnapalli picture rrkjonnapalli · Feb 9, 2017 · Viewed 10.8k times · Source
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

Answer

Halil RAŞO picture Halil RAŞO · Jan 8, 2018

first add this: compile 'io.apisense:rhino-android:1.0' to your app gradle file. Then type this snippet code

    TextView resultTextView = findViewById(R.id.result_text_view);
    String currentText = resultTextView.getText().toString();
    boolean valid = checkForValidity();
    double result=0;
    if(valid){
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
        try{
            result = (double)engine.eval(currentText);
        }catch(Exception e){
            Toast.makeText(this,"Exception Raised",Toast.LENGTH_SHORT).show();
        }
        currentText = currentText +"\n"+ "="+(result);
    }
    resultTextView.setText(currentText);