I have an EditText
in which I get numbers and need to convert them to a float
but still get the same eror - Null Pointer Exception
.
This is my code:
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) {
}
}
This is logcat :
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)
I tried it on a double
too.
I also had problem with null = ""
I read a lot about this but can`t find solution.