Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't read XML with correct encoding in Android
    text
    copied!<p>I have the following Java code that is supposed to get a XML in Android's <code>res/xml</code> folder and parse it.</p> <p>However, the <code>InputStream</code> is probably coming with an incorrect encoding, because it doesn't matter what I do, I won't get the correct text. An <code>org.xmlpull.v1.XmlPullParserException: Unexpected token</code> exception is thrown in line <code>parser.nextTag();</code> (<a href="http://pastebin.com/wRT46ZUP" rel="nofollow">more details here</a>). I already tried removing BOM (Byte Order Mark) and changing encoding. There is absolutely no invalid character in my XML file. Running this file in a Java project, instead of an Android project, works perfectly.</p> <p>I checked other question, but most of them seem to do the same thing that I do.</p> <p>My question: What is happening that prevents me from correctly reading the XML file?</p> <pre><code>//... InputStream is = getInstrumentation().getContext().getResources().openRawResource(com.example.test.R.xml.teste); //... public List&lt;Field&gt; parseDocument(InputStream in) { try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(in, "utf-8"); parser.nextTag(); // "org.xmlpull.v1.XmlPullParserException: Unexpected token" is thrown here. return readFeed(parser); } catch (Exception e) { e.printStackTrace(); } return fields; } </code></pre> <p>This is an example of XML that doesn't work: <a href="http://pastebin.com/i9vRpDW5" rel="nofollow">http://pastebin.com/i9vRpDW5</a> . When reading the file, I made sure I removed the BOM.</p> <p><strong>EDIT:</strong> Just to see how the XML is being read. I wrote the following method. I get a crazy text, regardless of the encoding I use.</p> <pre><code>public String readFile(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = ""; StringBuilder result = new StringBuilder(); while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload