0

I am trying to convert string to UTF-8 and store it in shared preferences but after getting its value I can't convert string which contains byte array to string

var myString ="hello world"
var bytes :ByteArray = myString.toUtf8Bytes()    

value of Bytes // [104, 101, 108, 108, 111, 32, 109, 121, 32, 119, 111, 114, 108, 100]

var result :String =   bytes.contentToString()

value of result // "[104, 101, 108, 108, 111, 32, 109, 121, 32, 119, 111, 114, 108, 100]"

How can I get the value of myString from the result?

thanks in advance

Majid Sadeghi
  • 180
  • 11
Mohamed Ali
  • 103
  • 1
  • 2
  • 9
  • Experimental, but see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/decode-to-string.html – Slaw Mar 25 '20 at 05:21
  • Does this answer your question? [Convert byte array to String](https://stackoverflow.com/questions/14950019/convert-byte-array-to-string) – MMG Mar 25 '20 at 05:24
  • See here: https://stackoverflow.com/questions/14950019/convert-byte-array-to-string – MMG Mar 25 '20 at 05:24
  • all this methods use bytearray as input , i want to use string of bytearray as input and get result string – Mohamed Ali Mar 25 '20 at 14:39

2 Answers2

0

You can use String(byteArray) to convert ByteArray to 'String' in kotlin

    val str = "hello world."
    val byte = str.toByteArray(Charsets.UTF_8)
    val newStr = String(byte)
    assert(str == newStr)
Mehdi Yari
  • 481
  • 3
  • 12
0

i found the answer here , error was in the way in storing data in shared Preferences and way to get it from string:

Storing ByteArray in sharedPreferences

Mohamed Ali
  • 103
  • 1
  • 2
  • 9