views:

320

answers:

1

I am posting some data to a server using DefaultHttpClient class and in the response stream I am getting a HTML file. I save the stream as a string and pass it onto another activity which contains a WebView to render this HTML on the screen:

response = httpClient.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuffer sb = new StringBuffer();
String line;

while((line=br.readLine())!=null){
    sb.append(line);
    sb.append("\n");
}

is.close();

Intent intent = new Intent(this,Trial.class);
intent.putExtra("trial",sb.toString());
startActivity(intent);

Log.i("SB",sb.toString());

In Second Activity, the code to load the WebView reads:

WebView browser = ((WebView)findViewById(R.id.trial_web));
browser.getSettings().setJavaScriptEnabled(true); 
browser.loadData(html,"text/html", "utf-8");

When I run this code, the WebView is not able to render the HTML content properly. It actually shows the HTML string in URL encoded format on the screen. Interestingly, If I copy the Loggers output to HTML file and then load this HTML in my WebView(using webview.loadurl(file:///assets/xyz.html)) everything works fine.

I suspect some problem with character encoding.

What is going wrong here? Please help.

Thanks.

A: 

Try using a BasicResponseHandler rather than converting it all into a string yourself. See here for an example. I am skeptical this will help, but it will simplify your code and let you get rid of the inefficient StringBuffer.

Also, you might try switching to loadDataWithBaseURL(), as I have had poor results with loadData(). The aforementioned example shows this as well.

CommonsWare
Thanks again Mark!This is the second time that loadDataWithBaseURL() has out done its overloaded counterpart. First, it was with rendition of inline CSS styles and now this. Why this idiosyncrasy, any idea?Also, thanks for reminding me of BasicResponseHandler, I had almost forgotten about it.Cheers!
Samuh
"Why this idiosyncrasy, any idea?" -- every time I think I have a pattern, something else crops up that breaks it, so now I just swear off `loadData()` outright.
CommonsWare