Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an integer array from an xml resource in Android program

Tags:

java

android

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.

like image 567
JERiv Avatar asked Jan 14 '10 14:01

JERiv


People also ask

Can integers be stored as resources in XML?

Integer. An integer defined in XML. Note: An integer is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine integer resources with other simple resources in the one XML file, under one <resources> element.

What is dimens XML in Android?

xml: The dimens. xml is used for defining the dimensions for different widgets to be included in the Android project.

What is an array in Android?

What is an Array? An array is a common data structure used to store an ordered list of items. The array elements are typed. For example, you could create an array of characters to represent the vowels in the alphabet: 1.


1 Answers

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.

like image 190
Dan Lew Avatar answered Oct 21 '22 12:10

Dan Lew