-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?

1
  • toMutableList ? In java I would do new ArrayList<String>(Arrays.asList(new String[] { } )); Commented Oct 3, 2022 at 12:03

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.