JERiv
JERiv

Reputation: 554

Get an integer array from an xml resource in Android program

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.

Upvotes: 26

Views: 58266

Answers (2)

M. AsadUllah
M. AsadUllah

Reputation: 11

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]

Upvotes: 0

Dan Lew
Dan Lew

Reputation: 87430

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.

Upvotes: 69

Related Questions