Execute Javascript inside Android

You may wondering why do we need to use javascript inside Android?? Imagine a situation when we are looking for a particular functionality, but there is no Android library implemented for that. However, we have a JS library for that. As an example if we need to add Jsonlogic kind of library to Android?? How would you do that?
There is a handy way to do that.We can execute Js function using Android. But only logic code. We cannot do any UI changes kind of things(as I know) using this libraries.
The library which we are using to execute JS is Rhino. You can download latest version from here.
After the library get downloaded , unzip the folder and copy the js.jar file and paste the jar to the libs folder inside the app folder in android project. Then right click the js.jar file and click “Add as Library”.If the “Add as Library” doesn’t appear open the app level gradle and add following code.
implementation files('./libs/js.jar')

Next we need to create a property file to add our JS function code. For that right click res folder and New -> Android resource directory and select the “Raw” directory. Inside the raw directory create a file called config.properties. Inside that add a property value like this.
jsExecute=var getRhinoHello=function(){return "hello rhino"}

Next open the class or activity and add the following function.
Let me explain the what is happening inside this function.
- Code Line 5–10 — In here I load the property file inside the raw folder.
- Code Line 12 — In here we get the property value. Inside the config.properties files we define the property name as a “jsExecute” . Therefore we need to use exact same name.
- Code Line 13 — In this line we define which function need to call.This must be same as the function name inside the config.properties. In the example we define function name as “getRhinoHello” inside the config.properties and we must use that function name here.
- Code Line 37– 41 — In here It will execute the JS function and return the value.
I hope you will get the idea about the function. Next we can call this function like this and see the output inside the logcat.
Log.d("Rhino", "onCreate: "+ runScript(this));
It will print “hello rhino” inside the logcat output.
If we want to pass parameter to the JS function we can add those values to the functionParams array like this.
Object[] functionParams = new Object[]{"cool"};
Then we need to modify JS function to accept parameters.
jsExecute=var getRhinoHello=function(param){return "hello rhino "+param}
I hope you would get a better idea about how to execute JS function inside tha android app.I hope to cover the more about performance and how to use with real world library in future articles.
Happy Android. 😄✌️
This is the tutorial video — https://youtu.be/qeiN2Xd-Dlw