I have the following code in my main activity:
var qNa_list = parseQuestions(loadJSONFromAsset("qna_list.json"))
fun loadJSONFromAsset(file_name:String): String? {
var json: String? = null
try {
val isis = assets.open(file_name)
val size = isis.available()
val buffer = ByteArray(size)
isis.read(buffer)
isis.close()
json = String(buffer, "UTF-8")
} catch (ex: IOException) {
ex.printStackTrace()
return null
}
return json
}
When I try to compile it I get the following error.
I fixed some other errors caused due to nullables, but this one is something I'm unable to decode.
Error:(127, 35) Type mismatch: inferred type is String but Charset was expected
I have changed some of the values to nullable to accomidate for the errors, but the json = String(buffer, "UTF-8")
(UTF-8) is always underlined in red.
This seems to have solved the issue.
It seems I need to specify the Charset
type object and not a string like UTF-8
.
1st method as mentioned by @Maroš Šeleng
Charset.forName("UTF-8")
Or, specify Charset.UTF_8
val charset: Charset = Charsets.UTF_8
json = String(buffer, charset)
According to javadoc, String
contructor accepts the second argument of type Charset
as seen here . You can use Charset.forName(String)
static method to create your Charset
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With