Reputation:
I have made an color-array containing 12 different colors in color.xml. But in my attempt to extract the colors and use them in the code I get null for all values in the array. I also tried to use the TypedArray solution with no difference. So what is wrong?
public void testColor(){
Resources resources = App.getAppContext().getResources();
String colors[] = resources.getStringArray(R.array.backgroundcolors);
//prints null
Log.d("TAG", " " + colors[3]);
//prints 12x null
for(String x : colors){
Log.d("TAG", " " + x);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testColor();
}
color.xml
<array name="backgroundcolors">
<item>#000000</item>
<item>#373737</item>
<item>#ffffff</item>
<item>#e6e6e6</item>
<item>#EAE1D8</item>
<item>#fd79a1</item>
<item>#ff0f68</item>
<item>#E849A1</item>
<item>#F7E84E</item>
<item>#FFB732</item>
<item>#48B1E3</item>
<item>#5dd95d</item>
</array>
Upvotes: 2
Views: 1811
Reputation: 18112
Solution 1
You should get the array as int array like this
int colors[] = resources.getIntArray(R.array.backgroundcolors);
Solution 2
If you want to read it as a String
array then
change
<array name="backgroundcolors">
to
<string-array name="backgroundcolors">
Upvotes: 0
Reputation: 17131
You can use
Color.parseColor(colors[i]))
Color.parseColor("#636161")
Upvotes: 0
Reputation: 157457
if you want to use getStringArray
, you should be useing
<string-array
as root tag instead of <array
and content should be placed in strings.xml
. Colors
are int
. You can use getIntArray to retrive an array
of int
from the res
Upvotes: 1
Reputation: 4490
change:
<array name="backgroundcolors">
to
<string-array name="backgroundcolors">
Upvotes: 5