我正在尝试实施微调器,并且在生产线上
spinner1.setAdapter(adapter1);
我收到以下错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)'
这是我的代码:
public class Temp extends Fragment implements AdapterView.OnItemSelectedListener{
private static final String[] paths1 = {"sam1", "sam2", "sam3", "sam4"},
paths2 = {"1", "2", "3", "4"};
private String name,seq;
private Spinner spinner1,spinner2;
private TextView tv1;
private ArrayAdapter<String> adapter1,adapter2;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View attendFragView = inflater.inflate(R.layout.fragment_attendance, container, false);
//Spinner 1 code
spinner1=(Spinner)attendFragView.findViewById(R.id.regPageFacSpinner1);
adapter1=new ArrayAdapter<String>(attendFragView.getContext(),R.layout.spinner_lay_notched,
paths2);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(this);
//Spinner 2 Code
spinner2=(Spinner)attendFragView.findViewById(R.id.regPageFacSpinner2);
adapter2=new ArrayAdapter<String>(attendFragView.getContext(),R.layout.spinner_lay_notched,
paths1);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(this);
final EditText et1 = (EditText) attendFragView.findViewById(R.id.secOtpFac);
tv1=(TextView)attendFragView.findViewById(R.id.attendPageFac5);
Button genOtp = (Button) attendFragView.findViewById(R.id.otpGenButFac);
genOtp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String dept= et1.getText().toString();
String name=spinner1.getSelectedItem().toString();
String seq=spinner2.getSelectedItem().toString();
JSONObject attendJSONSend = new JSONObject();
try {
attendJSONSend.put("name", name);
attendJSONSend.put("seq", seq);
attendJSONSend.put("dept", dept);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return attendFragView;
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
答案 0 :(得分:1)
正如异常所说,spinner1
为空,因为编译器尝试在空对象上使用setAdapter
。
为了解决此问题的建议。 (因为我经常面对)。
R.id.regPageFacSpinner1
上。祝你好运。