Mobile Development

MOZILLA RHINO – JavaScript Engine

By on April 3, 2017

What’s up people? How is it going? Hope everyone’s doing alright. So today I thought of doing an Android tutorial for you guys. As you all know I’m studying software engineering and we have a module called “Mobile Application Development” a.k.a MAD 😀 . And in that module we don’t have any in class tests or final exams. We just have two courseworks. That was one of the main reasons for me to select that module over server-side programming because in that they have two exams and no courseworks. Honestly I’d rather do courseworks than sitting for freaking exams.

Let’s keep that aside for awhile, In coursework 01 we were supposed to create a brain training game where the app generates random arithmetic expressions and the user has to guess the correct answer. When doing the project one of the biggest issues I had was to get the answers for the randomly generated expression. I could have written code for all the 4 levels separately but I wanted to reduce the lines of code at the same time.

Naturally I turned on to  google as one does and tried to find a solution. For java there is an inbuilt javascript engine called “Script Engine Manager”. What it basically does is, when you pass in a string expression it will output the answer. Unlucky for me it was not available on android. I even tried adding the library externally but got no where.

After hours and hours of searching I found a nifty little javascript library called “Rhino”.

WHAT IS RHINO?

Rhino is an open-source implementation of JavaScript written entirely in Java and managed by the Mozilla Foundation. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine.

useful links 

Step 01

First things first, open up a new Android studio project and give a name for your application, select the minimum sdk and pick a Activity and a name for the base activity.

I selected

  • App Name – Rhino
  • Minimum Sdk – API 14 (IceCreamSandwich)
  • Activity Type – Empty
  • Activity Name – HomeScreen

Of Course you guys are free to select anything you like.

NOTE : I’m assuming that you know how to create a new project in Android Studio. if not google 😛

Step 02

NOTE : The latest version of Rhino at the time of making this tutorial is 1.7.7.1. There may be a newer version, if there is please get that.
I will be using Android Studio for this tutorial and therefore I will copy the gradle dependency. If you are using maven or any other build tool copy the corresponding dependency.

Rhino Android tutorial - ScreenShot 1

Step 03

Paste the dependency you copied to the build.gradle (Module:app) script like in the screenshot below.

Rhino Android tutorial - ScreenShot 2

Step 03

Now that we’ve finished importing the library, let’s make the interface to input the arithmetic expression. What we need is just a simple EditText box and a Button. you can alternatively have a reset button as well but that is extra.

Following is the code snippet “activity_home_screen.xml” layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_converter__main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.apareciumlabs.brionsilva.rhino.HomeScreen">

    <TextView
        android:text="@string/arithmetictHelp"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="27dp" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/Grey39"
        android:digits="1234567890+-*/%.()"
        android:inputType="phone"
        android:textAlignment="center"
        android:id="@+id/arithmeticET"
        android:layout_marginTop="140dp"/>
    <Button
        android:text="Reset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginLeft="250dp"
        android:id="@+id/resetBtn"/>

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:textColor="@color/Red"
        android:id="@+id/errorTextView"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="24dp" />

    <Button
        android:text="@string/buttonText"
        android:textSize="70px"
        android:background="@color/OrangeRed"
        android:layout_width="200dp"
        android:layout_height="70dp"
        android:id="@+id/answerBtn"
        android:layout_alignBottom="@+id/errorTextView"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="65dp" />

    <TextView
        android:id="@+id/lblAnswer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />
    <TextView
        android:id="@+id/answerTextView"
        android:textSize="26sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/OrangeRed"
        android:layout_below="@+id/lblAnswer"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp" />

    <TextView
        android:id="@+id/lblDeveloper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="10sp"
        android:textAlignment="center"
        android:text="@string/developer"
        android:layout_below="@+id/answerBtn"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

You will get an interface similar to the below screenshot

Rhino Android tutorial - ScreenShot 3

Step 04

I have separated the script engine method in a class so that I could reuse in the future.
Create a class under your current package and name it “EvaluateEngine”.  And paste the following code in there.

Step 05

Let’s code the activity class now. What we have to do in this is just to get the input form the user, send it to the Evaluate class and display the returned answer.

package com.apareciumlabs.brionsilva.rhino;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 *
 * This activity will provide a simple UI for the user to input an
 * arithmetic expression and to find the answer to that exact question.
 *
 * @author brionsilva
 * @version 1.0
 * @since 18/03/2017
 */

public class HomeScreen extends AppCompatActivity {


    EditText arithmeticET;
    Button answerBtn,resetBtn;
    TextView errorTV,answerTV,answerLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);

        //initializing the text boxes, buttons etc.
        arithmeticET = (EditText) findViewById(R.id.arithmeticET);
        answerBtn = (Button) findViewById(R.id.answerBtn);
        resetBtn = (Button) findViewById(R.id.resetBtn);
        errorTV = (TextView) findViewById(R.id.errorTextView);
        answerTV = (TextView) findViewById(R.id.answerTextView);
        answerLabel = (TextView) findViewById(R.id.lblAnswer);


        //The onclick listener for the answer button
        answerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    if(arithmeticET.getText().toString().equals("") || arithmeticET.getText().toString().equals(null) ){

                        errorTV.setText("Please enter a value in the text box.");

                    }else {

                        //removes any text from the error text area if there's any
                        errorTV.setText(null);
                        //setting the answer label
                        answerLabel.setText(R.string.answer);

                        //Catching the entered value from the edit text box
                        String value = arithmeticET.getText().toString();

                        //Making an object of the RHINO evaluate engine class
                        EvaluateEngine evaluateEngine = new EvaluateEngine();

                        /*Passing the value to the rhino evaluate engine and storing the retuned
                        answer in a double variable*/
                        Double answer = evaluateEngine.evaluate(value);

                        //Displaying the answer in a text view
                        answerTV.setText(answer.toString());
                        }

                    }

            });

        resetBtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view){
                errorTV.setText(null);
                arithmeticET.setText(null);
            }
        });
    }
}

😀 😀 WE ARE DONE 😀 😀

Now test the app by typing any arithmetic expression and you should receive the accurate answer.

Rhino Android tutorial - ScreenShot 5
Octocat

DOWNLOAD MY GIT REPOSITORY –  https://github.com/brionmario/Android-Rhino-Example

I will be  back with another tutorial soon and till then stay safe. With ❤️ Brion.

TAGS
RELATED POSTS
1 Comment
  1. Janath Francisco

    April 23, 2017

    Great work!

Comments are closed.

BRION MARIO
Kalamulla, SRI LANKA

My name is Brion Mario. And I am a Developer/ Musician/ Designer/ Entrepreneur/ Blogger from Sri Lanka. I'm a Software Engineering undergraduate at University of Westminster. I enjoy writing very much and please tag along and read my journey......

ADVERTISING
Follow me on Twitter