70

I'm developing an Android app. I need to convert a string array into an ArrayList. I've read up on this, and all have cases where you add the values to the array in the java file. I have declared the string-array in the strings.xml file. My string-array is here:

<string-array name="Lines">
    <item>Red Line</item>
    <item>Blue Line</item>
    <item>Orange Line</item>
    <item>Green Line</item>
    <item>Brown Line</item>
    <item>Purple Line</item>
    <item>Pink Line</item>
    <item>Yellow Line</item>
</string-array>

I need to convert Lines into ArrayList. If I use this

List<String> Lines = new ArrayList<String>();

to declare the ArrayList, how can find the array list by ID, and store that as Lines?

hichris123
  • 10,145
  • 15
  • 56
  • 70

5 Answers5

181

Try this;

List<String> Lines = Arrays.asList(getResources().getStringArray(R.array.Lines));

and this for kotlin:

val Lines = resources.getStringArray(R.array.Lines).toList()
vasek
  • 2,759
  • 1
  • 26
  • 30
Melih Mucuk
  • 6,988
  • 6
  • 37
  • 56
4

In strings.xml, add string array

<string-array name="dashboard_tags">
    <item>Home</item>
    <item>Settings</item>
</string-array>

In your .java class access the string array like

List<String> tags = Arrays.asList(getResources().getStringArray(R.array.dashboard_tags));
Waqar UlHaq
  • 6,144
  • 2
  • 34
  • 42
4

If anybody wondering how to do the same in kotlin

val universities = arrayListOf<String>(*resources.getStringArray(R.array.universities))

universities will be ArrayList<String>

OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
0

This is the best practice without any warning

Add string array to arraylist:

Collections.addAll(Lines, getResources().getStringArray(R.array.Lines));

To add one ArrayList to another:

newList.addAll(oldList);
Silambarasan
  • 645
  • 1
  • 7
  • 13
0

use this

String[] parityArray = getResources().getStringArray(R.array.arrayName);
Zaman Rajpoot
  • 326
  • 2
  • 5
  • Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. - [From Review](https://stackoverflow.com/review/low-quality-posts/32238228) – Saeed Zhiany Jul 20 '22 at 05:07