null pointer exception in spinner adapter

i am trying to use this adapter on spinner , which is giving null pointer exception , kindly give ur worthy responses

ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, R.array.select_action_arrays);

and in my string.xml file

<string-array name="select_action_arrays">
        <item>alert1</item>
        <item>alert2</item>
        <item>alert3</item>
        <item>alert4</item>
        <item>alert5</item>
    </string-array>

here is the complete code line

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.select_action_arrays));
        spinnerSelectAction.setAdapter(adapter);
        spinnerSelectAction = (Spinner)findViewById(R.id.spinnerSelectAction);
        spinnerSelectAction.setAdapter(adapter);
        spinnerSelectAction.setOnItemSelectedListener(new OnItemSelectedListener() {
            int count=0;
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if(count >= 1){
                Toast.makeText(getBaseContext(),"inside on item selected ",Toast.LENGTH_SHORT).show();
                }
                count++;
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {}
        });

the spinnerSelectAction seems to be initialised

Upvotes: 0

Views: 1629

Answers (3)

khalil
khalil

Reputation: 743

you are adding to adapter before retrieving the spinner from the view, the 2 first instructions should be like that :

spinnerSelectAction = (Spinner)findViewById(R.id.spinnerSelectAction);
spinnerSelectAction.setAdapter(adapter);

Upvotes: 0

waqaslam
waqaslam

Reputation: 68187

You don't seem to initialize your adapter correctly. It should be something like:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
     android.R.layout.simple_spinner_item,
     getResources().getStringArray(R.array.select_action_arrays));

Upvotes: 2

Dipak Keshariya
Dipak Keshariya

Reputation: 22291

Write below code line

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.select_action_arrays));

instead of

ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, R.array.select_action_arrays);

may be it will solve your problem.

Upvotes: 1

Related Questions