Java – Loads an HTML file with UTF8 encoding from Assets into a TextView

Loads an HTML file with UTF8 encoding from Assets into a TextView… here is a solution to the problem.

Loads an HTML file with UTF8 encoding from Assets into a TextView

I

have an HTML file in UTF8 encoding (containing Persian characters) in the assets folder that I want to read and load into a TextView. I read a lot of posts such as load utf-8 text file, load HTML file into TextView , read UTF8 text file from res/raw and write this code :

try{
        InputStream inputStream = getResources().getAssets().open("htmls/salamati.html");
         I also try "UTF-8" but none of them worked
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream,"UTF8"));
        StringBuilder total = new StringBuilder();
        String html;
        while ((html = r.readLine()) != null) {
            total.append(html);
        }
         total contains incorrect characters
        textView.setText(Html.fromHtml(total.toString()));
    }
    catch (IOException exception)
    {
        textView.setText("Failed loading HTML.");
    }

But it shows incorrect characters!
I also tried converting total.toString() to a UTF8 String array and then adding it to the textView, but it didn’t work either

textView.setText(Html.fromHtml(new String(total.toString().getBytes("ISO-8859-1"), "UTF-8")));

There is no problem with the textView or emulator because when I load the HTML from the database, it displays the utf8 characters correctly!
So what should I do?

Solution

After a lot of searching and testing some other code, I ended up replacing my HTML file with another one. Surprisingly my code works fine! I investigated the previous HTML file and noticed that it has Unicode encoding!!!
So if you have the same problem, first check the encoding of your file and make sure it is correct.

Related Problems and Solutions