Reputation: 55
i have this code to read data from xml file written in Kotlin
val _is = resources.openRawResource(+R.xml.data)
val reader = BufferedReader(InputStreamReader(_is))
val data = StringBuffer()
val line = reader.readLine()
while (line != null) {
data.append(line!! + "\n")
//Log.d("aa",line.toString())
}
val resourceData = (data.toString())
the xml file data contains
<questions>
<question>aaa</question>
<question>bbb</question>
<question>ccc</question>
</questions>
and i always get wrond data and also had this exception what is the problem ?
Upvotes: 0
Views: 583
Reputation: 31710
You seem to be reading the same line over and over again. Because the loop will never end, you will eventually run out of memory and crash the program.
val line = reader.readLine() // 1
while (line != null) { // 2
data.append(line!! + "\n") // 3
}
1 - Have the reader read the next line of data into line
2 - If line is not null, keep going
3 - Append the line to data. Go to step 2.
What you need to do at the end of the loop is to read the next line, so the while loop can evaluate it for null. You also need to make line
a var
so you can change it.
var line = reader.readLine() // <-- Change val to var
while (line != null) {
data.append(line!! + "\n")
line = reader.readLine() // <-- Add this
}
Upvotes: 2