0

I have some string-array defined in the array.xml, and want to combine them in to a single List. I have try like this:

List<String> name_list;
name_list = Arrays.asList(getResources().getStringArray(R.array.name1));
name_list.addAll(Arrays.asList(getResources().getStringArray(R.array.name2)));

But error Caused by: java.lang.UnsupportedOperationException

array.xml

<string-array name="name1">
    <item>Peter</item>
    <item>Phooenix</item>
    <item>Ebele</item>
    <item>Alice</item>
</string-array>

<string-array name="name2">
    <item>Olivia</item>
    <item>Tai</item>
</string-array>

2 Answers 2

1

When you look at the Javadoc of Arrays you can see that the List returned by Arrays.asList(...) is only a Bridge to use an Array as a List and therefore is fixed size.

To solve your problem you can use something like this:

List<String> name_list = new ArrayList<>();
name_list.addAll(Arrays.asList(getResources().getStringArray(R.array.name1)));
name_list.addAll(Arrays.asList(getResources().getStringArray(R.array.name2)));
Sign up to request clarification or add additional context in comments.

2 Comments

But doing like this will become java.lang.NullPointerException
@MayWong The only way you'd get NPE with that code is if getResources() or getStringArray() return null, and you haven't included the code for either, so we can't help with that. If you need help with that, ask a new question, because this question has been answered.
0

Read the javadocs on Arrays.asList:

Returns a fixed-size list backed by the specified array.

So you're not allowed to call addAll in the second line of your code. Instead, you need to create your own List, and use addAll for both arrays on your own list.

2 Comments

Do you have any other ways to do this?
Other way could be, changing 2nd line to - name_list = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.name1)));

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.