I am creating an app where the users inputs data about their garden within fragments, it saves and outputs data on the home fragment. My problem is that I am trying to make a toast message when the user did not input any data.
Here's my code for the Thermometer fragment which takes in the temperature from the user and sends it to the home fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_thermometer, container, false);
Button enter = view.findViewById(R.id.btTemp);
EditText degrees = view.findViewById(R.id.nmDegrees);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tempo = degrees.getText().toString();
int temperature = Integer.parseInt(tempo);
if(!tempo.isEmpty()){
if(temperature > 100 || temperature < 40){
Toast.makeText(requireContext(), "Not Viable!!", Toast.LENGTH_LONG).show();
}
else {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Thermo", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sharedPreferences.edit();
ed.putInt("lastTemp", temperature);
ed.apply();
Toast.makeText(requireContext(), "Data Saved!!", Toast.LENGTH_LONG).show();
Bundle onOrOff = new Bundle();
getParentFragmentManager().setFragmentResult("dataFromThermometer", onOrOff);
degrees.setText("");
}
}
else {
Toast.makeText(requireContext(), "Cannot Be Blank!!", Toast.LENGTH_LONG).show();
}
//onOrOff.putInt("df1", Integer.parseInt(degrees.getText().toString()));
}
});
return view;
}
What I want to happen is for the toast message to appear but the app keeps closing instead Any help would be appreciated. (ignore comment in code)
I am creating an app where the users inputs data about their garden within fragments, it saves and outputs data on the home fragment. My problem is that I am trying to make a toast message when the user did not input any data.
Here's my code for the Thermometer fragment which takes in the temperature from the user and sends it to the home fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_thermometer, container, false);
Button enter = view.findViewById(R.id.btTemp);
EditText degrees = view.findViewById(R.id.nmDegrees);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tempo = degrees.getText().toString();
int temperature = Integer.parseInt(tempo);
if(!tempo.isEmpty()){
if(temperature > 100 || temperature < 40){
Toast.makeText(requireContext(), "Not Viable!!", Toast.LENGTH_LONG).show();
}
else {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Thermo", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sharedPreferences.edit();
ed.putInt("lastTemp", temperature);
ed.apply();
Toast.makeText(requireContext(), "Data Saved!!", Toast.LENGTH_LONG).show();
Bundle onOrOff = new Bundle();
getParentFragmentManager().setFragmentResult("dataFromThermometer", onOrOff);
degrees.setText("");
}
}
else {
Toast.makeText(requireContext(), "Cannot Be Blank!!", Toast.LENGTH_LONG).show();
}
//onOrOff.putInt("df1", Integer.parseInt(degrees.getText().toString()));
}
});
return view;
}
What I want to happen is for the toast message to appear but the app keeps closing instead Any help would be appreciated. (ignore comment in code)
Share Improve this question asked Mar 31 at 17:30 IsaIsa 193 bronze badges 1- "...the app keeps closing instead Any help would be appreciated." In general the crash log will provide details that should be included in the question. See Unfortunately MyApp has stopped. How can I solve this?. Apparently in this case it's a NullPointerException, so see also What is a NullPointerException, and how do I fix it?. – Markus Kauppinen Commented Apr 2 at 10:24
3 Answers
Reset to default 1Basically, this throws NullPointerException because the field is empty.
The application quits because android stops every app that throws any exception.
What you can do is check if the field is filled or empty before doing something with the value you get.
But you also will use a try block to convert the String you get to an int, what i recomend you here for more clear code is to use a try-catch block without if statement:
String temp=degrees.getText.toString();
try {
String input_str=degrees.getText().toString();
float degree=Float.parseFloat(input_str);
// do whatever you want with input
} catch (Exception e) { // catch all exception but you can also use multi-catch if you want
// code to handle null input or wrong input (user enters non-number characters or nothing).
// example:
runOnUiThread(new Runnable(){
@Override
public void run () {
// update ui to warn user
}
});
Edited Answer: Includes else clause.
Note: In this case, it's not a NullPointerException, since an empty string is not a null object; it is just a string, which is a non-null but empty string object. The exception in your case is a NumberFormatException. You can prevent it through try-catch statements.
The empty string cannot be parsed to an integer, which is a sign of NumberFormatException. That's why the exception is thrown, and your app is crashing. You can use try-catch statements in order to hinder any type of exception:
String tempo = degrees.getText().toString();
if (!tempo.isEmpty()) {
try {
int degree = Integer.parseInt(tempo);
} catch (Exception ignored) {
Toast.makeText(this, "Provide a valid integer.", Toast.LENGTH_LONG).show();
}
} else Toast.makeText(this, "Provide a valid integer.", Toast.LENGTH_LONG).show();
The issue you're facing is caused by the Integer.parseInt() method throwing a NumberFormatException when it tries to parse an empty string or invalid input (non-numeric values).
To prevent the app from crashing, you need to handle this exception properly using a try-catch block.
Here's the improved version of your code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_thermometer, container, false);
Button enter = view.findViewById(R.id.btTemp);
EditText degrees = view.findViewById(R.id.nmDegrees);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tempo = degrees.getText().toString();
if (tempo.isEmpty()) {
Toast.makeText(requireContext(), "Cannot Be Blank!!", Toast.LENGTH_LONG).show();
return;
}
try {
int temperature = Integer.parseInt(tempo);
if (temperature > 100 || temperature < 40) {
Toast.makeText(requireContext(), "Not Viable!!", Toast.LENGTH_LONG).show();
} else {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Thermo", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sharedPreferences.edit();
ed.putInt("lastTemp", temperature);
ed.apply();
Toast.makeText(requireContext(), "Data Saved!!", Toast.LENGTH_LONG).show();
Bundle onOrOff = new Bundle();
getParentFragmentManager().setFragmentResult("dataFromThermometer", onOrOff);
degrees.setText("");
}
} catch (NumberFormatException e) {
Toast.makeText(requireContext(), "Please enter a valid number", Toast.LENGTH_LONG).show();
}
}
});
return view;
}
Explanation:
Check for empty input: Before trying to parse the input, we first check if the input is empty and show a toast message accordingly.
Handle invalid input with try-catch: If the user enters a non-numeric value, the parseInt() method will throw a NumberFormatException, so we wrap it in a try-catch block to handle the exception gracefully and show a toast message informing the user to provide a valid number.
Temperature validation: If the parsed temperature is outside the valid range (less than 40 or greater than 100), we display a message saying it's not viable.