-1

I am having some trouble with formatting the results from A Room database. The results come out as one big, long, unbroken word, like this "texta,textb,textc" when I need them to be a string array, like this "texta","textb","textc" So my question in layman's terms is how do I break up the query result so that it works with my API.

here is how I implement database function and retrieve the data:

        mUserViewModel = ViewModelProvider(this).get(ViewModel::class.java)
        mUserViewModel.readSomeData.observe(viewLifecycleOwner, Observer { user ->
        val abc = user

I then parse it to the function where the data is POSTed to my API, this is how I ready it for export.

        val jArray = JsonArray()
        val element = JsonPrimitive(abc)
        jArray.add(element)

//        val element = JsonPrimitive("""texta","textb","textc""")//this works
        //above is what I was using to test the API when I still putting together the database.

I have tried a few things to try achieve the desired results:

the first was this:

val abc = user.split(",").toTypedArray().toString()

this turned the string into this ["[Ljava.lang.String;@e5daa3e"]

the second was this:

    val abc: String = user.toCharArray().map { it.toString() }.toString()

this made it so that each letter in the was broken up like this

["[t, e, x, t, a, ,, t, e, x, t, b, ,, t, e, x, t, c]"]

If anyone could tell me how to make text that I send to the API look like this "texta","textb","textc" I would be very appreciative.

if it helps the strings will always be 10 characters long.

thank you for your time.

3
  • Why do you need to call toString() method in val abc = user.split(",").toTypedArray().toString()? Commented Feb 21, 2021 at 19:27
  • because I get a type mismatch otherwise,JsonPrimitive wants a String. also I still get [Ljava.lang.String;@b0e4f60 if I just print it with out .tostring() Commented Feb 21, 2021 at 19:35
  • I don't code in kotlin, but I think u create another string, and then use a for loop to check each char in string, if that char == ",", you add the string to array, and set the string to empty, and on else you append char to the string. Commented Feb 21, 2021 at 19:38

1 Answer 1

1

One of the ways you can achieve this would be to use the Gson library to serialize the objects, here is an example:

val string = "texta,textb,textc"
val typedArray = string.split(",").toTypedArray()
val gson = Gson()
println(gson.toJson(typedArray ))

The output should look like this: ["texta","textb","textc"]

You can find more info in the following link https://github.com/google/gson

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.