I basically want to extract text from inside a webpage that is already loaded into the Webview
of the app.
Just as a trial, I built an app to count the occurrence of the Rupee symbol(₹) with the help of method from this post.
See the screenshot: App's Screenshot
But I am not able to make it work. The TextView
should show the number of '₹' symbols on the webpage but it stays unchanged.
I am a noob at Android and would highly appritiate any help :)
This is my code: (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");
}
}