Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AdapterView.OnItemSelectedListener is returning NULL view

I have the following code :

public class OnboardingActivity extends BaseLoggedInActivity
    implements CountryPickerDialog.ICountryPickerDialogUsers, AdapterView.OnItemSelectedListener {
private Spinner _countryCodeSpinner;

.
.
.
    private void setupCountrySpinner() {
        List<String> sortedCountryCodeList = CountryData.getInstance().getSortedCountryCodes();
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            R.layout.country_code_spinner_item,
            sortedCountryCodeList);
    _countryCodeSpinner.setOnItemSelectedListener(this);
    _countryCodeSpinner.setAdapter(adapter);
    _countryCodeSpinner
            .setOnTouchListener(getCountryCodeSpinnerTouchListener(_countryCodeSpinner));
    int position = getDefaultCountryNamePosition();
    if (position >= 0) {
        _countryCodeSpinner.setSelection(position);
    }
}

.
.
.
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    _logger.debug("Inside onItemSelected");
    view.setSelected(true);
}

I am getting a null pointer exception in the above function onItemSelected . Its returning NULL view. This trace i am receiving from one of the user but i am unable to reproduce it myself. What could be reason that onItemSelected is being called with a NULL view ?

Thanks

like image 710
rohit sharma Avatar asked Jan 07 '15 13:01

rohit sharma


1 Answers

It may be caused after the configuration change, e.g rotating the device. Your spinner is recreated and you are receiving a null parameter in the onItemSelected callback.

You can annotate the view in your implementation to be @nullable and then

if (view != null) {view.setSelected(true);}

If you are using Kotlin try this:

override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long){
    view?.isSelected = true
}
like image 120
Pitos Avatar answered Oct 20 '22 05:10

Pitos