Loyalar
Loyalar

Reputation: 2163

Receiving spinner from R.ID gives NullPointerException

I'm trying to access a spinner in my layout, and to set values on it from an array in my arrays.xml file. I'm using the default implementation of setting values on a Spinner, but I'm getting a NullPointerException, and I can not for the life of me realize why. My code is as following:

public class NewSandwich extends Activity {

    private Spinner breadtype;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SetupLayout();
        setContentView(R.layout.activity_new_sandwich);
    }

    private void SetupLayout() {
        breadtype = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.breadTypes,
            android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        breadtype.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_new_sandwich, menu);
        return true;
    }
}

And my XML for the spinner is as following:

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

Now, I get a NullPointerException from the spinner (i figured this out from debugging with test outputs), and I can't see why exactly. I've done this before, and I never got the exception from it before.

Upvotes: 0

Views: 87

Answers (1)

Glenn
Glenn

Reputation: 12809

Call first setContentView(R.layout.activity_new_sandwich) before SetupLayout() because your layout needs to be loaded so you can get reference to your Spinner

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_new_sandwich);
        SetupLayout();
    }

Upvotes: 1

Related Questions