Checking if spinner is selected and having null va

2019-02-18 06:37发布

问题:

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

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

is this a proper way? because i get FATAL EXCEPTION: main java.lang.NullPointerException on

String Name= spinnerName.getSelectedItem().toString();

I have declared it on Create

回答1:

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  { 

}


回答2:

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;
}


回答3:

if (spinner1.getCount()==0){
   Toast.makeText(getApplicationContext(),"spinner hasn't values",               
   Toast.LENGTH_LONG).show();
 }


回答4:

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();
    }


回答5:

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