How to get javascript value in Android

  • Replies:2
Divya
  • Forum posts: 2

May 10, 2016, 2:46:19 PM via Website

I am very new to Android and developing my first app. My Version is 6.0 and API veresion is 21.

My app is having a textbox and a button in its home page. I am putting my url and hit submit button so that a webview will loads this url.

In my url I included some javascript functions, they are defined to retuning some values.

I am trying to get that value and assign the value to other textbox.

I tried in two ways but none of them worked for me.

First
I created a new class as follows,

public class JsInterface {
private String val;

@JavascriptInterface
void receiveString(String value) {
    Log.d("This is what from JS-", value);
    val = value;
}
String Val() {
    return val;
}

}

My JS function

function goAndroid(Go Value to Script){ 
    var goString = "Hello " + Go Value to Script; 
    window.MyAndroidApp.receiveString(goString); 
} 

In mainActivity.java

WebView.addJavascriptInterface(new JsInterface(), "MyAndroidApp"); 
WebView.loadUrl("javascript:goAndroid('Go Value to Script')") 
//Below value is null.. 
System.out.println(new JsInterface().Val()); 

Here the system out comes nothing...

Second
As I am using API version 21, I followed the another way,

webView.evaluateJavascript("(function() { return goAndroid('My Value'); })();", new ValueCallback() { 
    @Override 
    public void onReceiveValue(String s) { 
    Log.d("LogName--------------", s); 
} 
}); 

Here I am getting a small popup which says " unfortunately, app has stopped". In LogCat I am getting the following error

05-10 17:36:13.922: E/AndroidRuntime(822): FATAL EXCEPTION: main 05-10 17:36:13.922: E/AndroidRuntime(822): java.lang.NoSuchMethodError: android.webkit.WebView.evaluateJavascript 05-10 17:36:13.922: E/AndroidRuntime(822): at com.example.asdf.MainActivity$5.onClick(MainActivity.java:209)

Thanks in advance.

— modified on May 10, 2016, 2:51:39 PM

Reply
Ashish Tripathi
  • Forum posts: 211

May 11, 2016, 10:45:45 AM via Website

As form the log the method is not there. Check the name for once may be you are using some different method name.

Reply
Divya
  • Forum posts: 2

May 11, 2016, 11:48:24 AM via Website

Ashish Tripathi

As form the log the method is not there. Check the name for once may be you are using some different method name.

This is webView's method. I double checked it. I typed webview and then dot then I used ctrl+space to get available methods and selected evaluateJavascript .

Reply