Ashutosh Shrestha Ashutosh Shrestha -3 years ago 48
Android Question

I am trying to get array of colors and use it for generating random colors on click but i keep getting java.lang.NumberFormatException: null

This is my color.XML and array I am using rainbow...

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="bright_pink">#FF007F</color>
<color name="orange">#FF7F00</color>
<color name="yellow">#FFFF00</color>
<color name="chartreuse">#7FFF00</color>
<color name="green">#00FF00</color>
<color name="spring_green">#00FF7F</color>
<color name="cyan">#00FFFF</color>
<color name="azure">#007FFF</color>
<color name="blue">#0000FF</color>
<color name="violet">#7F00FF</color>
<color name="magenta">#FF00FF</color>

<array name="rainbow">
<item>@color/bright_pink</item>
<item>@color/orange</item>
<item>@color/yellow</item>
<item>@color/chartreuse</item>
<item>@color/green</item>
<item>@color/spring_green</item>
<item>@color/cyan</item>
<item>@color/azure</item>
<item>@color/blue</item>
<item>@color/violet</item>
<item>@color/magenta</item>
</array>
</resources>


Here I am retrieving the color array and trying to set it as background color but I am getting the error Number Formal Null... It works when I make array in the class.. I have checked the array color and it gives values...

public class PracticeColor extends AppCompatActivity {
Random random;
TextView text;
Button button;
LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice_color);
final int[] colors=getResources().getIntArray(R.array.rainbow);
random= new Random();
button= (Button) findViewById(R.id.Change);
text= (TextView) findViewById(R.id.color);
layout= (LinearLayout) findViewById(R.id.back);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout.setBackgroundColor(colors[random.nextInt(colors.length-1)]);
}
});

}
}

Answer Source

Try this

 <string-array name="value">
    <item>@color/cardview_dark_background</item>
    <item>@color/colorAccent</item>
</string-array>

or

<integer-array name="value">
    <item>@color/cardview_dark_background</item>
</integer-array>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download