Roger
Roger

Reputation: 6527

Android spinner give a NullPointException

Any ideas why this code throws a NullPointException?

    Spinner spinnerLoadLayouts = (Spinner)this.findViewById(R.id.spnLoadLay);

    ArrayAdapter<CharSequence> adapter = 
    new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, new ArrayList<CharSequence>());

    adapter.add("aaa"); adapter.add("bbb");
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerLoadLayouts.setAdapter(adapter);

Thanks! :)

Upvotes: 0

Views: 115

Answers (2)

Nanne
Nanne

Reputation: 64399

If the error is on the last line, then spinnerLoadLayouts is NULL.

This could be because you can only do this

(Spinner)this.findViewById(R.id.spnLoadLay);

If the spnLoadLay view is actually in the current view (is available in an XML you have allready called setContentView on for instance). If you haven't put that on the screen, you can't find it using findViewById. You need to use an Inflater for that

Upvotes: 1

thomas
thomas

Reputation: 5649

I guess that the View or Activity cannot find R.id.spnLoadLay

Quote:

findViewById: Returns: The View that has the given tag in the hierarchy or null

Upvotes: 1

Related Questions