Question

I am super new to android programming. I am trying to figure out that when you press the button, it will display a toast message of the selected option that is in the spinner. Eclipse doesn't give me an error message but the program crashes whenever I try to run it in the emulator. Thanks for any help. Also, I added LogCat at the end of the code.

import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity 
{
    private NumberPicker np = (NumberPicker) findViewById(R.id.btnGetMonthFromSpinner);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadDisplay();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void loadDisplay()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        {
            // For API 14 or older
            String[] data = getResources().getStringArray(R.array.months);

            NumberPicker np = (NumberPicker) findViewById(R.id.pick_number);
            np.setMaxValue(data.length-1);
            np.setMinValue(0);
            np.setWrapSelectorWheel(true);
            np.setDisplayedValues(data);
        }
        else
        {
            // For API 13 or older
            Spinner spinner = (Spinner) findViewById(R.id.listofnumbers);
            // Create an ArrayAdapter using the string array and a default spinner layout
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.numberlist, android.R.layout.simple_spinner_item);
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // Apply the adapter to the spinner
            spinner.setAdapter(adapter);
            spinner.setOnItemSelectedListener(new SpinnerOnItemSelectedListener());
        }
    }

    public void showSelectedItem(View view)
    {
        // Called from onClick event in Button definition.
        // The Button only displays with NumberPicker layouts, not the Spinner.
        String[] entries = np.getDisplayedValues();
        Toast.makeText(getApplicationContext(), entries[np.getValue()], Toast.LENGTH_SHORT).show(); 
    }

    public class SpinnerOnItemSelectedListener implements OnItemSelectedListener 
    {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
        {
            // Either of the Toast statements will work. Spinner inherits the getSelectedItem()
            // from the AdapterView class, it returns an Object which I cast to a String.
            // We can't use the magical 'this' keyword in makeText() because we are in another
            // class, so we use getApplicationContext() instead.
            Toast.makeText(getApplicationContext(), (CharSequence) parent.getItemAtPosition(pos), Toast.LENGTH_SHORT).show();
            //Toast.makeText(getApplicationContext(), (String)spinner.getSelectedItem(), Toast.LENGTH_SHORT).show();
        }

        public void onNothingSelected(AdapterView<?> parent)
        {
            // Do nothing.
        }
    }

}

LogCat------------------------------------------------------------

01-15 06:58:23.238: D/AndroidRuntime(5105): Shutting down VM
01-15 06:58:23.238: W/dalvikvm(5105): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
01-15 06:58:23.258: E/AndroidRuntime(5105): FATAL EXCEPTION: main
01-15 06:58:23.258: E/AndroidRuntime(5105): java.lang.RuntimeException: Unable to start activity ComponentInfo{ca.mohawk.you.lab3/ca.mohawk.you.lab3.MainActivity}: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.NumberPicker
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.os.Looper.loop(Looper.java:137)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at java.lang.reflect.Method.invokeNative(Native Method)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at java.lang.reflect.Method.invoke(Method.java:511)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at dalvik.system.NativeStart.main(Native Method)
01-15 06:58:23.258: E/AndroidRuntime(5105): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.NumberPicker
01-15 06:58:23.258: E/AndroidRuntime(5105):     at ca.mohawk.you.lab3.MainActivity.onCreate(MainActivity.java:24)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.Activity.performCreate(Activity.java:5104)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-15 06:58:23.258: E/AndroidRuntime(5105):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-15 06:58:23.258: E/AndroidRuntime(5105):     ... 11 more
01-15 06:58:26.948: I/Process(5105): Sending signal. PID: 5105 SIG: 9
Was it helpful?

Solution

You need to initialize all Views after calling setContentView() so your NumberPicker is null. Change your initialization of

 private NumberPicker np = (NumberPicker) findViewById(R.id.btnGetMonthFromSpinner);

to

 NumberPicker np;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // here or anywhere after here
    np = (NumberPicker) findViewById(R.id.btnGetMonthFromSpinner);  

    loadDisplay();
}

Though, you initialize another picker with the same name in loadDisplay(). Not sure if you meant to do that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top