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++){
		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++){
		colors0[index] = colors_json.getString("label");
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);

without concern of hitting a nasty NullPointerException.



2 responses

1 05 2011

Thank you.

26 06 2016

I am getting error on spinnerMonth.setAdapter(adapterTab);


// Getting a reference to Spinner Widget containing list of countries
spinnerMonth = (Spinner) findViewById(;
// Getting a referece to TextView Widget, which displays the selected month from the spinner widget
textView = (TextView) findViewById(;
// Array adapter to set data in Spinner Widget
ArrayAdapter adapterTab = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, monthList);
Log.e(“Logger:Tabular”, ” DB list arrary monthList1 :::” + monthList);
// Setting the array adapter containing country list to the spinner widget
Log.e(“Logger:Tabular”, ” Bef new AdapterView monthList2 :::” + monthList);
AdapterView.OnItemSelectedListener monthSelectedListener = new AdapterView.OnItemSelectedListener() {

public void onItemSelected(AdapterView spinner, View container,
int position, long id) {
Log.e(“Logger:TabularActivity”, ” onItemSelected:Entry”);
textView.setText(“Chart for ” + strMonth[position]);
Log.e(“Logger:TabularActivity”, “:onItemSelected:strMonth” + strMonth);
Log.e(“Logger:TabularActivity”, “:Spinner[pos]>” + strMonth[position]);
Toast.makeText(getApplicationContext(), “Success : ” + strMonth[position], Toast.LENGTH_SHORT).show();
Log.e(“Logger:TabularActivity”, ” onItemSelected:Exit”);

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: