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.

About these ads

Actions

Information

One response

1 05 2011
Liviu

Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.

Join 261 other followers

%d bloggers like this: