java – Get an integer array from an xml resource in Android program-ThrowExceptions

Exception or error:

Just a quickie,

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

<?xml version="1.0" encoding="utf-8"?>
     <integer-array name="UserBases">

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.

How to solve:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *