-1

I want to be able to make my resources dynamic so that I can remove and add strings to it, for this I need to get the array programatically which I've done. However, I can't seem to figure out how to turn it into the correct array for this.

var array= resources.getStringArray(R.array.paintings)

I want to assign this array to a MUTABLE array.

However

var mutableArray: ArrayList<String> = ArrayList<String>()
mutableArray = array <------- Doesn't work
mutableArray.removeAt(2)

How do I make it mutable?

Coder
  • 340
  • 1
  • 9

2 Answers2

1

Well you have multiple options:

  1. You can use kotlin MutableList instead of ArrayList:

code:

val mutableList = array.toMutableList()
mutableList.removeAt(2)
  1. If you want to use ArrayList you can convert Array to ArrayList using two methods:

.

  • I- The first one is by adding all array elements to ArrayList using addAll():

code:

val mutableArray: ArrayList<String> = ArrayList<String>()
mutableArray.addAll(array)
mutableArray.removeAt(2)
  • II- The second one is by converting Array to List then converting that List to ArrayList:

code:

val mutableArray: ArrayList<String> = ArrayList(array.toList())
mutableArray.removeAt(2)
Mohamed Rejeb
  • 2,281
  • 1
  • 7
  • 16
1

First of all: Your array is already mutable, as it is an Array. your mutableArray is a MutableList, and not an array.

However, this does not make your resources dynamic. resources.getStringArray(R.array.paintings) loads your resources into an aray; changing that array does not change your resources but only that specific copy of it in memory.

If you want to have a persistant memory that you can read from or write to, you can do that with, for instance, Room or DataStore

Joozd
  • 501
  • 2
  • 14