5

I get an array from an API:

val pics = response.getJSONArray("pics")

pics contains like:

["https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/19\/55\/497173801955.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/10\/34\/242830811034.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/86\/23\/808728238623.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/90\/41\/146747399041.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/47\/41\/672475854741.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/63\/94\/771076926394.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/36\/42\/182330463642.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/29\/96\/948397532996.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/82\/54\/761385508254.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/41\/42\/142837364142.jpg","https:\/\/www.bla.com\/extern\/v\/pics\/mitte\/66\/25\/215324906625.jpg"]

I need to get that into an ArrayList<String>

This is one of multiple tries after converting JAVA solutions to kotlin:

val list = ArrayList<String>()
for (i in 0 until pics.length()) {
   list.add(pics.getJSONObject(i).getString("name"))
}

And then when I try to use list in ViewPager then I get type mismatch:

Required: Array<String>

Found:kotlin.collections.ArrayList<String

How to do this??

Why can't it be all just simple array() like in PHP smh this is all beyond annoying

0

1 Answer 1

11

Array<String> and ArrayList<String> are 2 different types.

What you need to provide is Array<String> but what you are actually providing is ArrayList<String>.

val list = Array(pics.length()) {
    pics.getString(it)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Answer doesn't help if you've got an actual JSONArray and want to convert to an Array<String>
@Justin could you please elaborate, JSONArray implements length() from List and has getString(int) method to retrieve a String element at nth position, how isn't this working for you?
Thank you for your reply. I've actually got this working now. I was just commenting on the fact that it wasn't working for me, using the json library. I ended up using the iterator and looping through and copying to an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.