Android Spinner, ArrayAdapter, and NullPointerException

12 01 2011

This might be obvious, if you’re bothering to read this, but when populating an Android Spinner with an ArrayAdapter, sourced by an array, the source array must not contain uninitialized elements.

For example, if you’re doing this:

String[] colors = new String[colors_json.length()+1];
for(int m=1; m<=colors_json.length(); m++){
	if(colors_json.has("label")){
		colors[m] = colors_json.getString("label");
	}
}

then you might encounter a case when there are uninitialized elements in colors.

Instead, you can try something like this:

String[] colors0 = new String[colors_json.length()+1];
int index = 1;
for(int m=1; m<=colors_json.length(); m++){
	if(colors_json.has("label")){
		colors0[index] = colors_json.getString("label");
		index++;
	}
}
colors = new String[index];
System.arraycopy(colors0, 1, colors, 1, index-1);

You can then continue safely to set:

colors[0] = "Color";
color_adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, colors);
color_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
color_spinner.setAdapter(color_adapter);

without concern of hitting a nasty NullPointerException.