22

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.

osjjames
  • 25
  • 1
  • 2
  • 8
Kotlinboy
  • 3,725
  • 4
  • 16
  • 27
  • in java you can use byteArray.toString() directly, i don't know whether kotlin allows it lik that. – Manoj kumar Nov 09 '17 at 10:11
  • 1
    @Manojkumar I think you got it wrong. The end result needs to be a `Charset` object. Not a char. But a Charset like "UTF-8" – Kotlinboy Nov 09 '17 at 10:56

2 Answers2

63

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)
Kotlinboy
  • 3,725
  • 4
  • 16
  • 27
4

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.

Maroš Šeleng
  • 1,600
  • 13
  • 28