简体   繁体   中英

Java get variable from another class in Android JavascriptInterface

I have two class and I want to get 'JSI.var' in MainActivity. Firstly i getting "" empty value when i button clicked. So, no log. Secondly i getting document.getElementsByName('name')[4].src) value. So, there are document.getElementsByName('name')[4].src) in next logs. How i get another class in @JavascriptInterface method.

in onCreate() method in MainActivity

  webview.getSettings().setJavaScriptEnabled(true);
  webview.addJavascriptInterface(new JSI(), "HTMLOUT");
  bt1.setOnClickListener(new OnClickListener(){
        public void onClick(View v){        
            for(int i=0;i<5;i++){
             webview.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByName('name')["+i+"].src);");
             Log.i("CODE : ",JSI.var);
             //or
             String str = JSI.var;}
        }});

JSI class

import android.webkit.JavascriptInterface;

public class JSI
{
    static String var="";

 @JavascriptInterface
 public static void processHTML(String html)
{    
    var=html;
 }
 }

Try this

static String var="";

public void onCreate() {
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(this, "HTMLOUT");
bt1.setOnClickListener(new OnClickListener(){
    public void onClick(View v){        
        for(int i=0;i<5;i++){
    webview.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByName('name')["+i+"].src);");
        }
    }
);
}

@JavascriptInterface
 public static void processHTML(String html){    
    var=html;
    Log.i("CODE : ",var);
 }     

This way you have the value in your activity when the javascript is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM