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-
How should I create ArrayList from resource string-array?
Simple do like this-
otherSeriesList = ArrayList<String>(Arrays.asList(*resources.getStringArray(R.array.get_other_series)))
* will pass the Array as vararg
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())
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()
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()
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().
Related
I'm new to kotlin, how could i create a list of object then to be user in a ListView in Android?
I have created a Class called Articolo.kt that looks like this:
data class Articolo(var barcode: String, var qty: Number)
So the data passed to it should be "barcode" and "qty" then the "barcode" will be a unique key and if an item with it exist i will need to increment "qty" instead of adding a new to the list.
Then here is my function where i make my controlls and adding the data to the class:
private fun addBarcode() {
val barcode = txtBarcode.text.toString()
val qta = txtQta.text.toString().toInt()
if (barcode.trim() == "") {
txtBarcode.requestFocus()
return;
}
Articolo(barcode, qta)
}
So at this point i have my object Articolo with my data, but how can i add it to a list / collection which i could access from my another fragment and use it in a ListView?
To create a list of data in kotlin you need to simple do it this way
var list = arrayOf(" here you pass the type of data you want")
**Int Example
var list = arrayOf(1,2,3)
** String example
var list = arrayOf("string1","string2,"string3");
If you want to use model class , you can use mutablelist
**you init a list
private var mylist : MutableList<Articolo>? = null
** then in your oncreate you reference it
mylist = mutableListOf()
** you can add your object class this way
var Articolo = Articolo("barcode","qty")
mylist.add(Articolo)
private var mylist = mutableListOf<Articolo>()
//find the same barcode and add the qty,otherwise add Articolo(barcode, qta) to list
mylist.find{
it.barcode==barcode
}?.let{
it.qty+=qta
}?:{
mylist.add(Articolo(barcode, qta))
}
find the same barcode and add the qty,otherwise add Articolo(barcode, qta) to list
Ps:as the question in unable-to-change-an-object-property-in-mutablelist,you should not use Number as a type
I have an array of nulls that I initialize with Strings. Then I have to pass it to a function that requires Array<String> instead of Array<String?>. So how can I go around this issue?
val list_names = arrayOfNulls<String>(plant_list.size)
for(item in plant_list){ list_names.plus(item.name) }
val myListAdapter = MyListAdapter(activity!!,list_names,list_types,list_images) // list_names must be Array<String>
I also want to mention that changing it in the Adapter would only complicate things, so I would like to do it all from here.
If you are sure that no null-values will be in your nullable array, you can simply (unsafe) cast it and it will work, e.g.:
val myListAdapter = MyListAdapter(activity!!,list_names as Array<String>,list_types,list_images)
If you have null values in there it depends a bit. One approach is then to first filter out the null-values and pass the resulting array, e.g.:
list_names.filterNotNull().toTypedArray()
// or in case you have different types in there and want only want a single matching one:
list_names.filterIsInstance<String>().toTypedArray()
But if you can: try to omit holding that array of nullable type in the first place. Can't you just filter out null values and collect the non-nullable only? That would probably the easiest and nicest way to collect the names as Array<String>, e.g.:
val list_names = plant_list.mapNotNull { it.name }.toTypedArray()
To answer your direct question you can get a new Array without nulls using this:
val nonNullListNames = list_names.filterNotNull().toTypedArray()
But there are other issues with your code. There's no reason to create the array of nulls and add items to it. Every time you call list_names.plus(item.name) in your loop, you are creating a new Array that still has the original set of null values plus your new item(s).
Instead you can directly create a list of non-null items from the collection you're getting items from, and convert it to an Array:
val nonNullNamesArray = plant_list.map { it.name }.toTypedArray()
If your plant names are nullable, use this:
val nonNullNamesArray = plant_list.mapNotNull { it.name }.toTypedArray()
You cannot have a arrayOfNulls and convert a Nullable to a NonNull object.
What I recommend to you is:
val list_names = mutableListOf<String>()
plant_list.foreach {
list_names.add(it.name)
}
val myListAdapter = MyListAdapter(activity, list_names, list_types, list_images)
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
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)
}
I am new to kotlin with Android Studio. I have written a function in kotlin which accepts an Arraylist as input and randomly shuffles it -
fun randomize(array: ArrayList<Any>) { ... }
I want this function to accept ArrayList of any type but calling with following arguments gives type mismatch error -
val arr = ArrayList<Int>()
// ...
randomize(array = arr) // Gives Error
How can I use ArrayList that accepts any type. Thanks for your help.
You need to make your function generic, like so:
fun <T> randomize(array: ArrayList<T>) {
// do whatever you want to your `ArrayList`
}
But if you don't have any specific way in mind for how to do the shuffling, you can just use the shuffle method of the standard library:
val arr = ArrayList<Int>()
// ...
arr.shuffle()
I hope to construct MutableList a based List b, how can I do in Kotlin?
BTW, Code A is wrong
var a:MutableList<MSetting>
var b:List<MSetting>
Code A
var a=mutableListOf(b)
Kotlin has a few versions of the toMutableList() extension function that should cover you. Check out the documentation here.
Basically, on any Collection, Interable, typed Array or generic Array, you can call .toMutableList() and it will creat a new MutableList (backed by ArrayList).
So in your code, you can do this (I'm showing types, you can leave them off):
var b: List<MSetting> = listOf(...)
var a: MutableList<MSetting> = b.toMutableList()
It is a generic and needs type information e.g.
var a = mutableListOf<Int>()
I tested at https://try.kotlinlang.org/#/
EDIT: I didn't read closely enough, what you want should be a toMutableList method.
var b = listOf(2, 3);
var a = b.toMutableList()
it's very easy:
val listB = listA?.toMutableList() ?: mutableListOf() // list B = A if (A != null), other wise, B = new empty list