Checking if spinner is selected and having null va

2019-02-18 06:39发布

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

5条回答
闹够了就滚
2楼-- · 2019-02-18 06:54
if (spinner1.getCount()==0){
   Toast.makeText(getApplicationContext(),"spinner hasn't values",               
   Toast.LENGTH_LONG).show();
 }
查看更多
等我变得足够好
3楼-- · 2019-02-18 07:00

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  { 

}
查看更多
Animai°情兽
4楼-- · 2019-02-18 07:01

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;
}
查看更多
Ridiculous、
5楼-- · 2019-02-18 07:15

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
查看更多
放荡不羁爱自由
6楼-- · 2019-02-18 07: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();
    }
查看更多
登录 后发表回答