26

Just a quickie,

i have an xml resource in res/values/integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <integer-array name="UserBases">
          <item>2</item>
          <item>8</item>
          <item>10</item>
          <item>16</item>
     </integer-array>
</resources>

and ive tried several things to access it:

int[] bases = R.array.UserBases;

this just returns and int reference to UserBases not the array itself

int[] bases = Resources.getSystem().getIntArray(R.array.UserBases);

and this throws an exception back at me telling me the int reference R.array.UserBases points to nothing

what is the best way to access this array, push it into a nice base-type int[] and then possibly push any modifications back into the xml resource.

I've checked the android documentation but I haven't found anything terribly fruitful.

2 Answers 2

69

You need to use Resources to get the int array; however you're using the system resources, which only includes the standard Android resources (e.g., those accessible via android.R.array.*). To get your own resources, you need to access the Resources via one of your Contexts.

For example, all Activities are Contexts, so in an Activity you can do this:

Resources r = getResources();
int[] bases = r.getIntArray(R.array.UserBases);

This is why it's often useful to pass around Context; you'll need it to get a hold of your application's Resources.

Sign up to request clarification or add additional context in comments.

2 Comments

Cool Beans! Thanks a lot. also whats the best way to add and remove items from the array (save editing raw xml) - essentially updating any changes from the int[] to the xml.
I'm not sure it's possible to update the xml from code; all resources xml is compiled into binary when you build the apk. You should make a new question on it, maybe someone else knows.
0

get an array from xml resources of android project can be accessed.

from array.xml

<string-array name="weather_values">
    <item>sunny</item>
    <item>cloudy</item>
    <item>rainy</item>
</string-array>

in Activity

String[] stringsArray = getApplicationContext().getResources().getStringArray(R.array.weather_values);

in Fragment

String[] stringsArray = getContext().getResources().getStringArray(R.array.weather_values);

for output in log

System.out.println("Array Values " + Arrays.toString(stringsArray));

output is

I/System.out: Array Values [sunny, cloudy, rainy]

Comments

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.