Checking if spinner is selected and having null value in Android

后端 未结 6 797
庸人自扰
庸人自扰 2021-01-12 09:27

I want to check first if spinner has null values based on the following:

String Name= spinnerName.getSelectedItem().toString();
if(Name != null) {     
} els         


        
相关标签:
6条回答
  • 2021-01-12 10:04

    Function for Spinner Item Selection

    SpinnerName.setOnItemSelectedListener(new OnItemSelectedListener() {             
                @Override
                public void onItemSelected(AdapterView<?> adapter, View v,int position, long id) {
                    // On selecting a spinner item
                    selected_item = adapter.getItemAtPosition(position).toString();
                }
                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                }
    });
    

    Check condition for selected Item

    if(selected_item.matches("")){
              //conditions accordingly  
    return;
    }
    
    0 讨论(0)
  • 2021-01-12 10:05
    if (spinner1.getCount()==0){
       Toast.makeText(getApplicationContext(),"spinner hasn't values",               
       Toast.LENGTH_LONG).show();
     }
    
    0 讨论(0)
  • 2021-01-12 10:13

    you can define a spinner for departure and destination like you did there, then inside a button onClickListener you can check for the value before starting a new activity for example:

    if(spinner1.getSelectedItem.toString.equalIgnoreCase(value) && spinner2.getSelectedItem.toString.equalIgnoreCase(value)) {
        Intent mIntent = new Intent(MainActivity.this, DetailActivity.class) startActivity(mIntent); 
    }else{ 
        //Show Toast here
    
    0 讨论(0)
  • 2021-01-12 10:19

    first you have to check either any item in the spinner selected or not and initialized or not

    if (modeOfReportingSpinner.getSelectedItem()!=null){
            modeOfString = modeOfReportingSpinner.getSelectedItem().toString();
        }
    
    0 讨论(0)
  • 2021-01-12 10:20

    spinnerName is null or if getSelectedItem() returns null, calling toString() will cause your app to crash for NPE

    String name= null;
    if(spinnerName != null && spinnerName.getSelectedItem() !=null ) {
       name = (String)spinnerName.getSelectedItem();
    } else  { 
    
    }
    
    0 讨论(0)
  • 2021-01-12 10:20

    Do not add toString(). If you add toString() it tries to convert null to String, then it throws Exception.

    if(spinnerName.getSelectedItem() !=null ) {
       name = spinnerName.getSelectedItem().toString();
    }
    
    0 讨论(0)
提交回复
热议问题