user750206
user750206

Reputation: 71

Displaying iso-8859-1 encoded content in WebView

I am obtaining HTML coded content from an SQlite database that I would like to display in a WebView . I am currently using:

public class ShowAbstracts extends Activity {
 public void onCreate(Bundle savedInstanceState) 
 {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
         String body = extras.getString(DatabaseHelper.KEY_BODY);
         WebView webview = new WebView(this);
         setContentView(webview);
         String summary = "<html><body> "+body+" </body></html>";
         webview.loadData(summary, "text/html", "iso-8859-1");
    }   
 }
}

It works in that it opens a WebView and displays the contents but I get strange characters and for some content it just crashes. The Database is ISO-8859-1 encoded. Is there any way to take care of the special characters in my database content and display them properly?

Thanks very much in advance!

Rik

Upvotes: 2

Views: 2398

Answers (2)

user750206
user750206

Reputation: 71

Success!

Solving this was a combination of 3 things:

  1. uri encoding the string
  2. pasting a head in the HTML string identifying utf-8 encoding
  3. installing LibreOffice which allowed the xls file used for generating the SQLite database to be saved as a csv file with utf-8 encoding (as far as I can tell not possible from MS Office Excel).

.

 public class ShowAbstracts extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
           String body = extras.getString(DatabaseHelper.KEY_BODY);
           WebView webview = new WebView(this);
           setContentView(webview);
           String summary = "<?xml version='1.0' encoding='utf-8'?><html><body>"+body+" </body></html>";
           String uri = Uri.encode(summary);
           webview.loadData(uri, "text/html", "utf-8");
        }   
    }
}

Upvotes: 5

thoredge
thoredge

Reputation: 12601

The api for WebView (http://developer.android.com/reference/android/webkit/WebView.html) says that the the data argument must be URI-escaped (http://developer.android.com/reference/java/net/URLEncoder.html).

Also, when you have a string, the encoding has already been done. You have to see to that the string is created using the correct encoding (for Android the default is UTF-8).

Upvotes: 0

Related Questions