Android: problems with getSelectedItem on a spinner

 ̄綄美尐妖づ 提交于 2019-12-11 10:42:20

问题


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[]{"MAIL@gmail.com"});
    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?


回答1:


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



回答2:


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.




回答3:


Maybe you should OnItemSelectedListener inseatead of a button. Android Spinner




回答4:


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/




回答5:


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[]{"MAIL@gmail.com"});
        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();
        } 

        } 
        }); 
    } 



回答6:


mSpinner.setSelected(true);

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



来源:https://stackoverflow.com/questions/29961987/android-problems-with-getselecteditem-on-a-spinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!