Change String-Array in Strings.xml to ArrayList

JavaAndroidArraysStringArraylist

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Try this;

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

and this for kotlin:

val Lines = resources.getStringArray(R.array.Lines).toList()

Solution 2 - Java

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));

Solution 3 - Java

If anybody wondering how to do the same in kotlin

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

universities will be ArrayList<String>

Solution 4 - Java

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhichris123View Question on Stackoverflow
Solution 1 - JavaMelih MucukView Answer on Stackoverflow
Solution 2 - JavaWaqar UlHaqView Answer on Stackoverflow
Solution 3 - JavaOhhhThatVarunView Answer on Stackoverflow
Solution 4 - JavaSilambarasanView Answer on Stackoverflow