Adam Varhegyi
Adam Varhegyi

Reputation: 9894

Load content to WebView

I would like to load this content to a WebView:

When i try like this:

myWebView.loadUrl(myUrlAdress);

It is loading the content but with all the html formatting visible, so i can see all the paragraph tags and the css style definition, so it is like a plain text.

When i try like this:

myWebView.loadDataWithBaseURL(myUrlAdress, null, "text/html", "UTF-8", null);

Simply nothing happens, webview stays blank without any data.

Last way i tried is:

myWebView.loadDataWithBaseURL(myUrlAdress, myUrlAdress, "text/html", "UTF-8", null);

This time the webview simply prints the link from i try to get the data, and nothing else.

Can somebody tell me which way to go and what is the problem?

Upvotes: 0

Views: 1304

Answers (1)

atw13
atw13

Reputation: 719

The problem is that the server is returning content type text/json, so the WebView, with loadUrl, doesn't know it should parse and display HTML. When you use loadDataWithBaseUrl, the data string has to be the actual HTML, not just the URL, which is what you're giving it. If you can't control the server output, then you need to download the data to a string and load that string as the data to the webview, like this as an inner class to your activity:

public class WebLoader extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            final HttpClient client = new DefaultHttpClient();
            final HttpGet request = new HttpGet(params[0]);
            BasicResponseHandler handler = new BasicResponseHandler();
            return client.execute(request, handler);
        }
        catch (Exception e) {
            // do something
            return null;
        }
    }

    @Override
    protected void onPostExecute(String html) {
        webview.loadDataWithBaseURL(url, html, "text/html", "UTF-8", null);
    }

}

Upvotes: 1

Related Questions