在片段中添加微调器

时间:2017-01-17 13:04:03

标签: android android-fragments nullpointerexception spinner

我正在尝试在运行时创建的片段中添加微调器。

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

我使用一个非常简单的代码,我怀疑它的上下文我没有做对。 以下是我的片段代码

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

这不是'空指针异常'问题,而是关于在片段中添加数据和使用上下文的更多信息。

1 个答案:

答案 0 :(得分:1)

添加getActivity()它将起作用。

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

删除此行

 spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);