0

I'm trying to add a spinner in a fragment that's created at run time. I keep getting a crash with

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference

Im using a very simple code and I suspect its the Context that I'm not getting right. Following is my Fragment code

  @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_devices,container,false);

    spinner_device_settings = (Spinner) view.findViewById(R.id.spinner_device_settings);
    spinnerItemsArray = new ArrayList<>();

    String dev_settings = "12,15,19,26,23"; // this is hard coded temporarily

    String[] devsettarray = dev_settings.split(",");

    for (String sett : devsettarray){
     Log.d("log", "onCreateView: " + sett); //i get the proper values here, separately.
        spinnerItemsArray.add(sett);
    }

    ArrayAdapter<String> spinnerAdapter =  new ArrayAdapter<>(inflater.getContext(),android.R.layout.simple_spinner_item,spinnerItemsArray);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner_device_settings.setAdapter(spinnerAdapter); // error is thrown on this line

    return view;
}

This is not a 'Null Pointer Exception' issues but more about adding data and using contexts in a fragment.

jamian
  • 1,544
  • 2
  • 16
  • 25
  • Your xml frag_devices may not have a spinner with id pinner_device_settings.If this doesn't work , post your xml frag_devices. – Arpan Sharma Jan 17 '17 at 13:06
  • It does. I've added a spinner in the Frag xml that i am inflating – jamian Jan 17 '17 at 13:10
  • 1
    Make sure you are not lost between the Spinner and Appcompat spinner stuff. These things are a real pain. Make sure you are using the same type both in your XML and code. For the sake of clarity, post your spinner xml – Dibzmania Jan 17 '17 at 13:16
  • matter of fact, That could be the issue – jamian Jan 17 '17 at 13:17

1 Answers1

1

Add getActivity() it will work.

 ArrayAdapter<String> spinnerAdapter =  new ArrayAdapter<>(getActivity(),android.R.layout.simple_spinner_item,spinnerItemsArray);  

Remove this line

 spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
santosh kumar
  • 2,952
  • 1
  • 15
  • 27