10

I have declared ArrayList like,

var otherSeriesList = ArrayList<String>()

And trying to get data from resource by following,

otherSeriesList = ArrayList<String>(Arrays.asList(resources.getStringArray(R.array.get_other_series)))

But I am getting error. Please see the image- enter image description here

How should I create ArrayList from resource string-array?

3
  • 3
    If you have an array foo you can do otherSeriesList = arrayListOf(*foo) (note the spread operator * which takes care of passing the array as a vararg). Commented Jan 11, 2018 at 13:13
  • I have done like this. Please put it as answer. Commented Jan 11, 2018 at 13:22
  • One of the people that posted an answer has added this method to their answer. Commented Jan 11, 2018 at 13:39

5 Answers 5

12

Simple do like this-

otherSeriesList = ArrayList<String>(Arrays.asList(*resources.getStringArray(R.array.get_other_series)))

* will pass the Array as vararg

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

1 Comment

This solution is not only look massive, but it also makes redundant Arrays.asList call
5

Just use ArrayList(resources.getStringArray( ... ).toMutableList()) instead.

If you don't need to use ArrayList exactly in your code, then you can change type of property to MutableList<String> and call resources.getStringArray( ... ).toMutableList()

Or you can use spread operator on your array and create ArrayList via call arrayListOf(*context.resources.getStringArray())

2 Comments

using mutableListOf is also an option
@Zoe yep, but only in case when type of property is MutableList. And even in such case better and easier to call toMutableList() instead of combining mutableListOf with spread operator
1

You can to declare it as MutableList(). Also cast that StringArray to String before that.

var otherSeriesList: MutableList<String> = Arrays.asList(resources.getStringArray(R.array.get_other_series).toString())

Or you can do it like,

var otherSeriesList: MutableList<String> = resources.getStringArray(R.array.get_other_series).toMutableList()

Comments

0

you can create an extension function

 private fun Array<String>.getAsArrayList(): ArrayList<String> {
    val list = ArrayList<String>()
    this.forEach { it->list.add(it) }
    return list
}

and call it like this

val  list = resources.getStringArray(R.array.array).getAsArrayList()

Comments

0

If you have an array, simply call toList() on it.

val arr = arrayOf(1, 2)
val list = arr.toList()

Alternatively, there’s also a toMutableList() extension available.

Note that you can declare lists in Kotlin like this:

val list = listOf<String>(1, 2)

To be sure to get an ArrayList, use arrayListOf().

Comments

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.