Java – Why getResources().getStringArray(R.array.***); When I move the *.xml file to a different folder than res/values, the method doesn’t work

Why getResources().getStringArray(R.array.***); When I move the *.xml file to a different folder than res/values, the method doesn’t work… here is a solution to the problem.

Why getResources().getStringArray(R.array.***); When I move the *.xml file to a different folder than res/values, the method doesn’t work

I have a strange question.
I have an array in the xml file:

res/values/difficulties.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <string-array name="difficulty_names">
        <item> @string/easy </item>
        <item> @string/medium </item>
        <item> @string/hard </item>
        <item> @string/insane </item>
        <item> @string/preposterous </item>
        <item> @string/ludicrous </item>
    </string-array>
</resources>

To initialize this array, I used this method:

String[] difficultiesNamesArray = getResources().getStringArray(R.array.difficulty_names); 

This is very effective. Until I move this file to a different folder. Since then, this method has not worked. The new path is:

res/arrays/difficulties.xml

I was wondering, how to localize this file and use the getStringArray() method again on this relocated xml file.

Or you can even use the getResources().getStringArray(R.array.****) method. If not, how do I read an array from this different path.
My guess is that it needs to implement XMLParser. But I don’t know how to do it using this simple array.

In developer.android.com I found this information:

String Resources

  • Define strings, string arrays, and plurals (and include string formatting and styling). Saved in res/values/ and accessed from the
    R.string, R.array, and R.plurals classes.

So I think this is somehow related to my problem, I can’t use the getStringArray() method for files that are located in a different path than res/values/.
But that’s just my gut feeling. I do not know.

Am I right? Can arrays be read from different paths.xml? If how?

Solution

res/values/ is a system reserved folder. So, when you add arrays, strings, etc. in that folder, an android Resource (“R”) class will be generated based on the type of value you want to add. Therefore, if you use a different folder structure, the same “R” class value is not generated.

You can quote here Learn more about the “R” class being generated

If you want to

maintain your values in your own folder structure, then you may want to put it in the “assets” folder in any folder structure you want. THEN TO ACCESS IT, YOU NEED TO PARSE THE XML YOURSELF, WHICH IS VERY NOT RECOMMENDED.

You can refer to the following link to see how to read files from the Assets folder.

My suggestion is to name your string file in a way similar to the folder structure. In your case, consider naming res/values/arrays_difficulties.xml

Related Problems and Solutions