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
Related
I get this ArrayList named items containing several Data class in Adapter.
[DiaryCard(writeTime=2023-01-04, name=신혜정, stepCount=0, mood=2131230894, diary=안녕하세요),
DiaryCard(writeTime=2023-01-04, name=신혜정, stepCount=11, mood=2131230894, diary=hi),
DiaryCard(writeTime=2023-01-04, name=신태건, stepCount=0, mood=2131230898, diary=대단히 반갑습니다)]
I want to sort them by key 'writeTime' before I bind this data to View in ViewHolder.
var items = items
var sortItems = items.sortedBy { it.writeTime }
inner class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var userWriteTime: TextView = itemView.findViewById(R.id.userWriteTime)
var userNameView: TextView = itemView.findViewById<TextView>(R.id.userName)
var userStepCountView: TextView = itemView.findViewById<TextView>(R.id.userStepCount)
var userMoodView: ImageView = itemView.findViewById<ImageView>(R.id.userMood)
var userDiaryView: TextView = itemView.findViewById<TextView>(R.id.userDiary)
fun bind(position: Int) {
Log.d("결과아", "items: $items")
Log.d("결과아", "sortItems: $sortItems")
userWriteTime.text = sortItems[position].writeTime
userNameView.text = sortItems[position].name
userStepCountView.text = "${sortItems[position].stepCount}보"
userMoodView.setImageResource((sortItems[position].mood ?: 2131230873).toInt())
userDiaryView.text = sortItems[position].diary
}
}
So I create var sortItems which sort items by using sortedBy.
And I link this sortItems var to function bind instead of items.
But it won't work.
When I print items and sortItems, the items shown above ArrayList contains 3 DiaryCard Data classes.
But sortItems show empty ListArray, [].
So How can I sort ArrayList by one component of DataClass?
Plus, my writeTime is String value coming from LocalDate.now().
How can I sort them by LocalDate.now() in order for the most recent data to come first?
I use Kotlin, please help me with detailed code.
Thank you!
items.sortByDescending { item -> item.writeTime }
The method sortByDescending mutates the original list sorting it descending using the size of the list as selector to make the comparison between elements.
You can use sortByDescending to get recents one first. Documentation
var sortItems = items.sortByDescending { it.writeTime }
I am trying to extract from a list all element which are not in the sublist already created. I cannot make it work using .filterNot because it filtering on the overall data class store in the list.
var subList2 = allList.filterNot { subList1.contains(it) }.toMutableList()
but allList and subList are a list of data class defined as :
data class Food(
var name: Name,
var state: State
)
As of now, using this code, the sublist2 can contain food that are in sublist1 because state is different.
I want the filter to be done only on name so the sublist2 only contain food which is not in the sublist1 whatever the state is.
Any idea ?
Try to map the subList1 names:
val subList1Names = subList1.map { it.name }
var subList2 = allList.filterNot { it.name in subList1Names }.toMutableList()
I am trying to add elements of arrayList into model class arrayList. But at the end, all of the elements of model class becoming the last added element. what am I missing? thanks
this is model class
class ChaplainAvailableTimesModelClass(
var time: String? = null,
val isBooked: Boolean = false,
val patientUid: String? = null
) {
}
I defined the arraylists here
private var chaplainAvailableTimes = ArrayList<ChaplainAvailableTimesModelClass>()
private var temporaryTimes= ArrayList<String>()
this is the adding part
val chaplainAvailableTimesModelClass = ChaplainAvailableTimesModelClass()
dbSaveAvailableTimes = db.collection(chaplainCollectionName).document(chaplainUserId)
for (k in 0 until temporaryTimes.size){
chaplainAvailableTimesModelClass.time = temporaryTimes[k]
chaplainAvailableTimes.add(chaplainAvailableTimesModelClass)
}
The problem in your code is this:
val chaplainAvailableTimesModelClass = ChaplainAvailableTimesModelClass() /// <-----
dbSaveAvailableTimes = db.collection(chaplainCollectionName).document(chaplainUserId)
for (k in 0 until temporaryTimes.size){
chaplainAvailableTimesModelClass.time = temporaryTimes[k]
chaplainAvailableTimes.add(chaplainAvailableTimesModelClass)
}
You are instantiating a chaplainAvailableTimesModelClass once before the for loop and using the same instance when adding it to your arraylist. You need to create different instances of chaplainAvailableTimesModelClass per the amount (temproraryTimes.size) that you desire.
So, depending on what you want to do, it might be worthwhile to move the instantiation of the chaplainAvailableTimesModelClass inside of the for loop.
what I want to do is update the recyclerview information as I enter some text to filter information. I use "notifydatasetchange" but it does not show anything. The filtered information is ok.
This is my global list
var productList: MutableList<Product> = mutableListOf()
this is the adapter function which displays the first time ok
private fun buildProductAdapter(filter: String) {
productList = Product().getProductsByFilter(filter)
productListAdapter = ProductListAdapter(applicationContext, productList, cashOrCredit)
rcvProducts.adapter = productListAdapter
}
then, when the text has changed
private fun notifyProductListFilterChanged() {
val filter: String = if (edtSearchProduct.text.toString() != "") edtSearchProduct.text.toString() else ""
productList.clear()
productList = Product().getProductsByFilter(filter)
productListAdapter!!.notifyDataSetChanged()
}
But when I get to that function, it just does not display anything.
This happens because you change the reference of your variable to a new list
productList = Product().getProductsByFilter(filter)
while the adapter still holds the reference to the old one.
Instead, add your new items to the same list:
productList.addAll(Product().getProductsByFilter(filter))
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().