sachit
sachit

Reputation: 1138

Getting Error while creating spinner programmatically

I have a button in my xml. I want to pop up spinner programmatically not from xml after

clicking on button. but when i am clicking on the sbutton it is giving me an error.

Log output-:

android.view.WindoManager

$BadTokenException: Unable to add window--token null is not for an application

Here is my code:

b1.setOnclickListener(new View.OnClickListener(){
public void onClick(View v) {
List<String> list = new ArrayLIst<String>(Arrays.asList("a","s","d"));
Spinner t = new Spinner(getApplicationContext());
ArrayAdapter<String> adp = new ArrayAdapter<String>   

(getApplicationContext(),android.R.layout.simple_spinner_item,list);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
t.setAdapter(adp);
t.performClick();

Upvotes: 0

Views: 256

Answers (4)

subbu
subbu

Reputation: 51

       List<String> list = new ArrayList<String>(Arrays.asList("a","b","c"));
       t = new Spinner(ActivityName.this);
       ArrayAdapter<String> adp = new ArrayAdapter<String>   

      (ActivityName.this,android.R.layout.simple_spinner_item,list);
      adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      t.setAdapter(adp);
          t.performClick();

Upvotes: 1

MKJParekh
MKJParekh

Reputation: 34301

Give a try : Change the getApplicationContext() with ActivityName.this

I am sure this will give the correct token to show up the spinner.

Upvotes: 2

Blundell
Blundell

Reputation: 76496

You need to add the Spinner to your Activity/View.

Try this:

ViewGroup v = (ViewGroup) findViewById(R.id.your_id_for_a_linear_layout); // or relatvie etc
v.addChild(t);
t.performClick();

Upvotes: 0

knvarma
knvarma

Reputation: 974

I think you have put this code into onCreate(). The layout is not yet attached to window and you are trying to show window. So the window manager throws an exception. I didn't find any code to add this spinner to showing layout.

Upvotes: 0

Related Questions