Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a spinner dynamically

I was struggling to create a spinner dynamically. I had it on the page but every time I tried to select an option it would blow up. My original code is at the bottom. I fixed it by moving the addSpinner() function outside of the inner class and changing

Spinner newSpinner = new Spinner(getApplicationContext());

to

Spinner newSpinner = new Spinner(this);

It's fixed but I have no idea what it didn't work initially. Can anyone explain? (apologies if it's a noob question - I am new to both Java and android)

public class SpotManageActivity extends Activity
{
    private SimpleCursorAdapter mSpots;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reminder_manage_activity);

        Button add_new_button = (Button) findViewById(R.id.add_new_spot_button);
        add_new_button.setOnClickListener(new ButtonOnClickListener());

    }

    public class ButtonOnClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v)
        {
            addSpinner();
        }

        private void addSpinner()
        {
            LinearLayout layoutHolder = 
                (LinearLayout) findViewById(R.id.layout_holder);

            LinearLayout spinnerHolder = new LinearLayout(getApplicationContext());
            spinnerHolder.setOrientation(LinearLayout.HORIZONTAL);

            spinnerHolder.setLayoutParams(
                new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT, 
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
            Spinner newSpinner = new Spinner(getApplicationContext());
            newSpinner.setLayoutParams(
                new Spinner.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            newSpinner.setAdapter(mSpots);

            layoutHolder.addView(spinnerHolder);
            spinnerHolder.addView(newSpinner);

            // A non-internal spot was selected
        }

    }

}
like image 1000
guided1 Avatar asked Mar 18 '26 00:03

guided1


1 Answers

I am not sure at all, but if in the stack trace you're getting something about a wrong context, it's probably because a Spinner, when clicked, opens a Dialog, and a Dialog needs an Activity context.

For more info:

  • Android - what's the difference between the various methods to get a Context?
  • Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context
like image 62
bigstones Avatar answered Mar 20 '26 13:03

bigstones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!