Android R.integer returns the wrong value. Very large value that is called from mem when creating an array

I declared several integer values โ€‹โ€‹in xml and should use the values โ€‹โ€‹in the class to determine the size of the object array.

<?xml version="1.0" encoding="utf-8"?> <resources> <!-- Default Object Count --> <item format="integer" name="item1" type="integer">3</item> <item format="integer" name="item2" type="integer">1</item> <item format="integer" name="item3" type="integer">1</item> </resources> 

I use the above values โ€‹โ€‹in my class as follows

 public class InitialiseObjects { // For now static number of objects initialized private String TAG = "INIT_OBJECTS"; int ITEM1_COUNT = R.integer.item1; int ITEM2_COUNT = R.integer.item2; int ITEM3_COUNT = R.integer.item3; private Item1[] item1Objs = new Item1[ITEM1_COUNT]; private Item2[] item2Objs = new Item2[ITEM2_COUNT]; private Item3[] item3Objs = new Item3[ITEM3_COUNT]; } 

I expect ITEM * _COUNT to be 3,1,1 respectively for positions 1,2,3. However, I get 2131034112, 2131034113, 2131034114 respectively

What is wrong here?

Android 2.2 [API-8] is used

+4
source share
3 answers

R.integer.item1 is a resource identifier and therefore a very large and arbitrary integer.

The value you are looking for is getContext().getResources().getInteger(R.integer.item1);

Therefore, you cannot get them in static code.

You should use lazy initialization in your code:

 private Item1[] item1Objs; public Item1[] getItem1Array(Context context) { if (item1Objs == null) { int count = context.getResources().getInteger(R.integer.item1); item1Objs = new Item1[count]; } return item1Objs; } 
+10
source

Do the following:

 Resources res = getResources(); int maxSpeed = res.getInteger(R.integer.max_speed); 

See here: http://developer.android.com/guide/topics/resources/more-resources.html#Integer

+1
source

The reason is that any R.integer. * is a generated integer value, it is like id, which is associated with your value declared in xml

You better call

 getResources().getInteger(R.integer.*); 
+1
source

Source: https://habr.com/ru/post/1446765/


All Articles