Android: problems with getSelectedItem on a spinner
Asked Answered
C

6

1

I have a Spinner, and put the selected item in the body of a mail. this is my code:

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

    Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);

// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,     R.array.Taglie, 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);
    spinnerTaglia.setPrompt("Seleziona la taglia!");

// Apply the adapter to the spinner
    spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
            adapter,
            R.layout.contact_spinner_row_nothing_selected,
            // R.layout.contact_spinner_nothing_selected_dropdown, // Optional
            this));

    final String taglia = spinnerTaglia.getSelectedItem().toString();


    Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
    btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){

        public void onClick(View arg0) {

    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
    i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
    i.putExtra(Intent.EXTRA_TEXT   , "Taglia: "+taglia);
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

    }
    });
}

The application start correctly in the emulator and the debugger show me nothing (I'm using Android Studio) but when i click on the button that take me in this activity the application crash and the Android Studio's Debugger show me a java.lang.NullPointerException in the row:

final String taglia = spinnerTaglia.getSelectedItem().toString();

how can i fix this?

Callable answered 30/4, 2015 at 7:49 Comment(1)
it looks like no item is selected, so getSelectedItem() returns null. shouldn't you add a onSelection callback or something like this?Lenni
L
3

getSelectedItem() returns null if there is nothing selected on your spinner and calling toString() is making your application crash. Get rid of

final String taglia = spinnerTaglia.getSelectedItem().toString();

and in your onClick do:

if (spinnerTaglia.getSelectedItem() == null) {
      return;
}
String taglia = spinnerTaglia.getSelectedItem().toString();
// the other code
Leatriceleave answered 30/4, 2015 at 7:55 Comment(9)
Ok, with this implementation at click on button the module with the spinner open correctly, but now it show me another error after the spinner's choice, when i click on the button btnCompilaOrdine: java.lang.IllegalStateException: Could not find a method compilaOrdine(View) in the activity class com.example.valeria.flexibilaapp.Modulo for onClick handler on view class android.support.v7.internal.widget.TintButton with id 'btnCompilaOrdine'Callable
You can either add a public void btnCompilaOrdine(View view) {} method in your Activity Modulo, or open the layout you are using in your Activity Modulo, look for the onClick property and get rid of itLeatriceleave
I don't remember for what reason, but i had put android:onClick="compilaOrdine" in the XML attribute of the button. I have cancelled it but now at click on button nothing happens!Callable
there isn't a real reason. It another way to set an onClickListener for that view. You can do it either through the xml or programmatically calling setOnClickListenerLeatriceleave
So, the java code: Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine); btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){ public void onClick(View arg0) { } can be replaced by XML attribute android:onclick="compilaOrdine , right? So, if i delete the XML attribute it must work?Callable
The xml button is: <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Compila l'ordine" android:id="@+id/btnCompilaOrdine" android:layout_gravity="center_horizontal" /> and the java code is the one you see in the original question. Now when i click on the button nothing happens!Callable
wait, chill out. Help me understand what's going on. Did you still have btnCompilaOrdine.setOnClickListener in your Activity ?Leatriceleave
Yes, i have deleted android:onclic="compilaOrdine" from XML, and the java code is the same that you see above whit the add of the "if" that you have suggested.Callable
the class you posted is called Modulo ?Leatriceleave
L
1

Move the line

final String taglia = spinnerTaglia.getSelectedItem().toString();

to inside your OnClickListener

Currently, you're trying to read the selected item before anything has been selected. You should also ensure that getSelectedItem() isn't returning null because, unless you enable / disable the btnCompilaOrdine button (when an item is selected), the user can press the button without selecting an item in the spinner.

Lakin answered 30/4, 2015 at 7:56 Comment(0)
E
0

Maybe you should OnItemSelectedListener inseatead of a button. Android Spinner

Engineering answered 30/4, 2015 at 7:58 Comment(0)
R
0

It seems that Item is returned with NULL value try to Invoking the method from a null object.

TheNullPointerException is a RuntimeException and thus, the Javac compiler does not force you to use a try-catch block to handle it appropriately.

Hope this will help you to solve your issue.

for further reference visit the link below:- http://examples.javacodegeeks.com/java-basics/exceptions/java-lang-nullpointerexception-how-to-handle-null-pointer-exception/

Revolute answered 30/4, 2015 at 8:0 Comment(0)
P
0

Your are getting the selected item before the actual rendering of the spinner. It depends on device to device that how fast it renders the screen. Rather then getting the selected item in getSelectionItem() in the onCreate() method try out to do it in the onClickListener() of your Button.

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

        Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);

    // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,     R.array.Taglie, 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); 
        spinnerTaglia.setPrompt("Seleziona la taglia!");

    // Apply the adapter to the spinner 
        spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
                adapter, 
                R.layout.contact_spinner_row_nothing_selected,
                // R.layout.contact_spinner_nothing_selected_dropdown, // Optional 
                this));




        Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
        btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){

            public void onClick(View arg0) {

        //Get the Selected item from the spinner
        final String taglia = spinnerTaglia.getSelectedItem().toString();
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
        i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
        i.putExtra(Intent.EXTRA_TEXT   , "Taglia: "+taglia);
        try { 
            startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
        } 

        } 
        }); 
    } 
Prowler answered 30/4, 2015 at 8:4 Comment(0)
R
0
mSpinner.setSelected(true);

If you implement this with your spinner, it will not give null.

Romeyn answered 28/8, 2017 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.