I'm trying to extract some graphics from a web page to show them in a webview of my Android application.
I am basing myself on the example of this post How to display a part of the webpage on the webview android but I still do not succeed, any idea what I'm doing wrong or how I could solve it?
This in my app code:
import android.os.AsyncTask;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
WebView mWebView;
Handler uiHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView)findViewById(R.id.activity_main_webview);
//Activamos en JavaScript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//Activamos el zoom
webSettings.setBuiltInZoomControls(true);
mWebView.setWebViewClient(new MyWebViewClient());
new BackgroundWorker().execute();
}
// load links in WebView instead of default browser
private class MyWebViewClient extends WebViewClient {
@RequiresApi(21)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return false;
}
}
private class BackgroundWorker extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
getGraphics();
return null;
}
public void getGraphics() {
try {
Document htmlDocument = Jsoup.connect("http://amunet.com.mx/wordpress/index.php/graficas-de-3-tomas/").get();
//Document htmlDocument = Jsoup.connect("http://datos.botonmedico.com/pruebaJSOUP.html").get();
//Document htmlDocument = Jsoup.connect("http://darebee.com/").get();
// Element element = htmlDocument.select("div#div1 > h3").first();
Element element = htmlDocument.select("div#chart8").first();
//Element element = htmlDocument.select("div#gkHeaderMod > div.darewod").first();
System.out.println("Elemento: "+element);
// replace body with selected element
htmlDocument.body().empty().append(element.toString());
final String html = htmlDocument.toString();
uiHandler.post(new Runnable() {
@Override
public void run() {
mWebView.loadData(html, "text/html", "UTF-8");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction()== KeyEvent.ACTION_DOWN){
switch(keyCode){
case KeyEvent.KEYCODE_BACK:
if(mWebView.canGoBack()){
mWebView.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}