【发布时间】:2017-10-24 00:45:07
【问题描述】:
我有一个EditText,我在其中获取数字并需要将它们转换为float,但仍然得到相同的错误 - Null Pointer Exception。
这是我的代码:
public class Basic extends Fragment implements AdapterView.OnItemSelectedListener {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.basic, container, false);
Spinner spinnerLenght = (Spinner) view.findViewById(R.id.spinnerLenght);
spinnerLenght.setOnItemSelectedListener(this);
ArrayAdapter<String> lenghtAdapter;
lenghtAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.basic_string_lenght));
lenghtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerLenght.setAdapter(lenghtAdapter);
return view;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String itemLenght = parent.getItemAtPosition(position).toString();
EditText editTextLenght = (EditText) view.findViewById(R.id.editTextLenght);
float floatLenght;
floatLenght = Float.parseFloat(editTextLenght.getText().toString());
float result_mm = 0;
if (itemLenght.equals("mm")){
result_mm = floatLenght * 1000;
}
Toast.makeText(parent.getContext(), (int) result_mm, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
这是日志猫:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dusan.unit, PID: 5181
java.lang.NullPointerException
at com.example.dusan.unit.Basic.onItemSelected(Basic.java:46)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:956)
at android.widget.AdapterView.access$200(AdapterView.java:49)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:920)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
我也在double 上尝试过。
我也遇到了null = "" 的问题
我阅读了很多关于此的内容,但找不到解决方案。
【问题讨论】:
标签: android string nullpointerexception android-edittext