0

I am attempting to scoop some utf-8 encoded (Spanish text) data from a sqlite database and then display it in a webview. The essential parts of the code are as follows:

String web_data_string = cursor.getString(0);
webview.loadData(web_data_string, "text/html", "utf-8");

The string is a word containing all normal characters except one which should be a lower-case e+acute. In the webview all the normal characters appear correctly, but the e+acute appears as two characters, an A+tilde followed by a copyright symbol.

Where did I go wrong?

EDIT: +1 to dd619 for a solution that can be made to work, but I am hoping for a more general solution where there may be many more special characters, in other languages too.

Mick
  • 8,284
  • 22
  • 81
  • 173

3 Answers3

2

This does the trick...

    String web_data_string = cursor.getString(0);
    webview.loadData(utf_eight_to_web(web_data_string), "text/html", "utf-8");

    String utf_eight_to_web(String str)
    {
        String ans = "";
        Character c;
        for(int i = 0;i<str.length();i++)
        {
            c = str.charAt(i);
            if (c <= 127)
            {
                ans += str.charAt(i);
            }
            else
            {
                ans += String.format("&#%d;",(int)c);
            }
        }
        return ans;
    }
Mick
  • 8,284
  • 22
  • 81
  • 173
1

If you have any special character/letter then you need to replace it with respective escape character sequence.

Have a look at this useful link.

I had the same problem with some Spanish characters e.g.á and i solved it by replacing á with \u00e1

e.g. if you want to print "Parámetros" then simply do.

String str="Parámetros";
str=str.replace("á","\u00e1");
Log.i("MyClass",str);

Now you can str in database or java or in C++ or any web platform!

dd619
  • 5,910
  • 8
  • 35
  • 60
1

The Mick's answer could be improved using StringBuilder:

private String utfEightToWeb(String str)
{
    StringBuilder stringBuilder = new StringBuilder();
    Character c;
    for (int i = 0; i<str.length(); i++) {
        c = str.charAt(i);
        if (c <= 127) {
            stringBuilder.append(str.charAt(i));
        } else {
            stringBuilder.append(String.format("&#%d;",(int)c));
        }
    }
    return stringBuilder.toString();
}
Mikalai Daronin
  • 8,590
  • 2
  • 35
  • 47