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?

5 Answers 5

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()
2
  • What if i want an ArrayList insted of a List? Nov 16, 2018 at 11:39
  • 6
    @G.Ciardini ArrayList<String> lines = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.Lines))); Feb 12, 2019 at 10:47
5

If anybody wondering how to do the same in kotlin

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

universities will be ArrayList<String>

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

use this

String[] parityArray = getResources().getStringArray(R.array.arrayName);
1
  • Please read How do I write a good 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 Jul 20, 2022 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.