简体   繁体   中英

java.lang.NullPointerException when not selected spinner on android

I used this code to show a prompt when the user did not select the spinner on my application :

      protected View getView(int position, View convertView, ViewGroup parent) 
      throws IllegalAccessException {

        if( position<0 ) {
            final TextView v= (TextView) ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
                    inflate(android.R.layout.simple_spinner_item, parent, false);
            v.setText("--select one--");
            return v;
        }
        return obj.getView(position,convertView,parent);
    }

I got one problems when I want to try save my values from spinner when it's not selected, it always returns null pointer from this line, such as:

  hubungan_pp.getSelectedItem().toString(),
  hubungan_pp.getSelectedItemPosition()

I have 55 spinners on my application, and when I click button save and I'm not selected my spinner it always return null pointer. My question is how I can get a null value when user not click my spinner?

Probably hubungan_pp.getSelectedItem() is null because the spinner is not selected. So when you call .toString() on it, it's logical that it returns a NullPointerException.

You can either put a default selection text like 'Select One' or default value. Or you can handle Null value check as follows:

String selected_text = "none"
if (hubungan_pp.getSelectedItem() != null)
{
    selected_text = hubungan_pp.getSelectedItem().toString();
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM