我基本上想要从已加载到应用的Webview
的网页中提取文字。
就像试用一样,我借助this post的方法构建了一个应用来计算卢比符号(₹)的出现次数。
查看截图: App's Screenshot
但我无法使其发挥作用。 TextView
应该在网页上显示“₹”符号的数量,但它保持不变。
我是Android的菜鸟,并且会高度赞赏任何帮助:)
这是我的代码: (MainActivity)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static TextView count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count = (TextView) findViewById(R.id.textView);
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface {
@JavascriptInterface
@SuppressWarnings("unused")
public void processHTML(String html) {
// process the html as needed by the app
int occ = 0;
for(int i = 0 ; i < html.length() ; i++)
if(html.charAt(i) == '₹')
occ++;
MainActivity.count.setText(occ);
}
}
final WebView browser = (WebView) findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");
}
});
/* load a web page */
browser.loadUrl("https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=buy+chocolate");
}
}
答案 0 :(得分:0)
让它发挥作用。两个小问题:
您正在JavaScript调用的函数中进行UI调用。这是不允许的。
将MainActivity.count.setText(occ);
替换为
runOnUiThread(new Runnable() {
@Override
public void run() {
count.setText(String.valueOf(occ));
}
});
setText(int)
需要资源ID,因此您需要先转换为String。(您还需要从static
)
count