Reputation: 149
I'm trying to make a copy of List<>
from a variable declared in Application class object. Problem for me is that I'm unable to make a separate copy. Any update which I do on second variable also updates the application variable. Below is the code I'm using:
var app: MyApplication
private var taskItems: ArrayList<TaskItem>? = null
override fun onCreate(savedInstanceState: Bundle?) {
app = applicationContext as MyApplication
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
taskItems = app.selectedTask?.items!!
}
fun updateCount(idx: Int, quantity: Int){
taskItems?.get(idx)?.count = quantity
// This updates both taskItems and app.selectedTask.items
// I want to update only taskItems variable
}
I only want to update the taskItems
variable from function updateCount() and not the app variable app.selectedTask.items
. I've tried following changes in onCreateView function:
taskItems= ArrayList<TaskItem>(app.selectedTask?.items!!)
taskItems= ArrayList()
taskItems!!.addAll(app.selectedTask?.items!!)
taskItems= ArrayList()
for (item in app.selectedTask?.items!!) {
taskItems!!.add(item)
}
But none of the above code worked for me. Any help is really appreciated.
Upvotes: 1
Views: 166
Reputation: 1129
Try following code:
taskItems= ArrayList()
app.selectedTask?.items!!.forEach {
taskItems.add(it.copy())
}
Upvotes: 2