My android app is crashing due to two empty edittext fields [duplicate] - android

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Issue with empty EditText
(3 answers)
convert EditText to float - android eclipse
(6 answers)
when EditText is empty and click calculateButton, app crashes
(3 answers)
How to stop the app crashing when String is empty
(4 answers)
Closed 5 years ago.
#Override
public void onClick(View v)
{
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
}
Above is my code, when I leave any one of them empty, it crashes.How to get over it.

Just check whether user has entered anything or not and then parse your value:
if(!Total.getText().toString().matches(""))
float num1 = Float.parseFloat(Total.getText().toString());

Try Using Try...Catch
float num1 = 0.00f;
float num2 = 0.00f;
try {
num1 = Float.parseFloat(Total.getText().toString());
num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
catch(NumberFormatException ex) {
//Handle Non Float Exception
Toast.makeText(getApplicationContext(), "Invalid input !",Toast.LENGTH_LONG).show();
}

try this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Total.getText().toString().trim().equals("")&&!Done.getText().toString().trim().equals("")){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});

You can apply condition if EditText is not empty then your code is run like that
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
String total=Total.getText().toString();
String done=Done.getText().toString();
if (!total.isEmpty() && !done.isEmpty()) {
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}else {
Toast.makeText(OpenFile.this, "Fill values", Toast.LENGTH_SHORT).show();
}

Firstly Check whether you find editText properly or not
After that also check isEmpty condition for avoiding NullPointer Exception
if (!editText1.getText().toString().isEmpty() && !editText2.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
}

check for empty text, if not empty than perform calculation
if(!Total.getText().toString().isEmpty() && !Done.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});

Related

How do I use long Decimal Numbers in my input fields? Currently it crashes due to an improperly formatted string?

num1 and num2 are input values that need to have long decimal points but when it parses the string the decimal gets stripped and it crashes. Any assistance would be appreciated.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBuyInButton = (Button) findViewById(R.id.addBuyInButton);
addBuyInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText feeNumEditText = findViewById(R.id.feeNumEditText);
EditText buyInNumEditText =
findViewById(R.id.buyInNumEditText);
TextView targetTextView = findViewById(R.id.targetTextView);
Blockquote right around here is where I run into problems...
int num1 =
Integer.parseInt(feeNumEditText.getText().toString());
int num2 =
Integer.parseInt(buyInNumEditText.getText().toString());
int num3 = 3;
int num4 = 100;
int num5 = num1 + num3;
int num6 = num5 / num4;
int num7 = num6 * num2;
int num8 = num7 + num2;
targetTextView.setText(num8 + "");
}
});
}
}
Had to use float and DecimalFormat to get desired effect.
String str2 = buyInNumEditText.getText().toString();
float num1 = Float.parseFloat(str1);
float num2 = Float.parseFloat(str2);
float num3 = 3;
float num4 = 100;
float num5 = num1 + num3;
float num6 = num5 / num4;
float num7 = num6 * num2;
float num8 = num7 + num2;
DecimalFormat formatter = new DecimalFormat("##.########");
String num9 = formatter.format(num8);

Error while Execution android studio

I have developed an calculator app. It needs two inputs num1 and num2.
When i give the 2 inputs the arithmetic process is working good. But, when i click any buttons(add,sub,mul,division) without any inputs, the app has closed and shows the error "Unfortunately calc has stopped.
public void onButtonClick(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
TextView t1 = (TextView)findViewById(R.id.textView);
float num1 = Integer.parseInt(e1.getText().toString());
float num2 = Integer.parseInt(e2.getText().toString());
float sum = num1 + num2; t1.setText(Float.toString(sum));
}
Just add a validation method before Onclick
private boolean validation(){
int error = 1;
if(num1.getText().toString.equals("")){error = error + 1;}
if(num2.getText().toString.equals("")){error = error + 1;}
if(error == 0){return true;} else { return false; }
}
I guess its because you're having null value in the 'editText' and you're converting null value to float without checking for the condition that it is not null.
So before conversion. check if the editText is null. Like this:
if(e1.getText().toString()!="" && e2.getText().toString()!="")
{
float num1 = Float.parseFloat(e1.getText().toString());
float num2 = Float.parseFloat(e2.getText().toString());
}
And you should use 'Float' for conversion and not 'Int'
Try this
String mNum1="",mNum2="";
mNum1=e1.getText().toString();
mNum2=e2.getText().toString();
if(!mNum1.equalsIgnoreCase("") && !mNum2.equalsIgnoreCase("") )
{
float num1 = (float) Double.parseDouble(mNum1);
float num2 = (float) Double.parseDouble(mNum2);
float sum = num1 + num2;
System.out.println("sum"+String.valueOf(sum));
t1.setText(String.valueOf(sum));
}

Arithmetic Operation

hello guys I am having this problem. When I enter a score in the editText, I want the app to generate the equivalent in the Textview(w/ red box). But the app crashes with this code.
private void calculateEquivalent(){
double x , y;
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString());
if (x >= y * 0.65){
double equivalent = (Math.round((100 + (72 * (x - y)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
} else {
double equivalent = (Math.round((75 + (23 * (x - y * 0.65)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
}
}
The error is empty string when convert from string to double
In this code
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString());
May be total_score.toString() or editScore.getText().toString() was empty
And what is type of total_score variable
You have a problem when trying to convert empty string to a double. You should check first that the text field is not empty and that it doesn't contain characters by catching NumberFormatException
As the error log suggests, you need to make sure that you have proper values before you start the calculation.
So before calling this function you need to check for below conditions:
try
{
if((total_score.toString() != null && !total_score.toString().isEmpty()) && (editScore.getText().toString()!=null && !editScore.getText().toString().isEmpty()))
{
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString()); //chances of getting a Numberformat exception if entered value is not a number
calculateEquivalent();
}
}
catch(NumberFormatException e)
{
//Toast.makeText(m_context, "You entered a wrong value,Please enter only numeric values", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch(Throwable e)
{
e.printStackTrace();
}
Also in your calculateEquivalent(); method, you need to make sure that value of y should not be zero.
Hope this helps you :)
Hey #callmejeo the main problem with the function you wrote above is that you are coverting "NULL" values into String so one thing you can do is that to HANDLE exception.
private void calculateEquivalent(){
try{
double x , y;
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString());
if (x >= y * 0.65){
double equivalent = (Math.round((100 + (72 * (x - y)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
} else {
double equivalent = (Math.round((75 + (23 * (x - y * 0.65)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
}
}
catch(Exception e){
Toast.makeText(this,"Please Enter some value",Toast.LENGTH_LONG).show();
}
}
Thanks a lot guys without your suggestions I probably stuck in this problem :)
and then I've come up with this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_student_quiz);
TextWatcher inputTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
calculateEquivalent();
}
};
editScore.addTextChangedListener(inputTextWatcher);
}
private void calculateEquivalent(){
try {
y = Double.parseDouble(total_score);
x = Double.parseDouble(editScore.getText().toString());
if (x >= y * 0.65){
double equivalent = (Math.round((100 + (72 * (x - y)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
} else {
double equivalent = (Math.round((75 + (23 * (x - y * 0.65)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), "Please Enter a Number", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}

How to handle not filled EditText in Android

I want to code a simple calculator with 3 inputs (NUM1,NUM2,NUM3), 3 buttons(SUM,SUB,MUL) and 1 RESULT text plane. In my app if I give all inputs, the app works correctly. However if I don't give any input for 1 field, I encounter app stopped error. I want to make my app work with any number of inputs.
Here is my code.
public void onButtonClickSum(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sum = num1 + num2 + num3;
t1.setText(Integer.toString(sum));
}
public void onButtonClickSub(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sub = num1 - num2 - num3;
t1.setText(Integer.toString(sub));
}
public void onButtonClickMul(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int mul = num1 * num2 * num3;
t1.setText(Integer.toString(mul));
}
You need to put null or empty checks before you parse the input as integers
Try making the EditText objects fields, since you are reusing them in each method
Example:
// Fields
private EditText mEditText1 = (EditText)findViewById(R.id.editText);
private EditText mEditText2 = (EditText)findViewById(R.id.editText2);
private EditText mEditText3 = (EditText)findViewById(R.id.editText3);
private TextView mTextView = (TextView)findViewById(R.id.textView2);
public void onButtonClick(View v){
int num1 = 0;
int num2 = 0;
int num3 = 0;
String e1 = mEditText1.getText();
String e2 = mEditText2.getText();
String e3 = mEditText3.getText();
if(!e1.isEmpty()) {
num1 = Integer.parseInt(e1);
}
if(!e2.isEmpty()){
num2 = Integer.parseInt(e2);
}
if(!e3.isEmpty()){
num3 = Integer.parseInt(e3);
}
int sub = num1 - num2 - num3;
mTextView.setText(Integer.toString(sub));
}
Change from
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
to
int num1 = 0, num2 = 0, num3 = 0;
int num1_error = 0, num2_error = 0, num3_error = 0;
try{
num1 = Integer.parseInt(e1.getText().toString());
}Catch(Exception e){
num1_error = 1;
}
try{
num2 = Integer.parseInt(e2.getText().toString());
}Catch(Exception e){
num2_error = 1;
}
try{
num3 = Integer.parseInt(e3.getText().toString());
}Catch(Exception e){
num3_error = 1;
}
// for addition
int sum = 0;
if(num1_error == 0){
sum += num1;
}
if(num2_error == 0){
sum += num2;
}
if(num1_error == 0){
sum += num3;
}
t1.setText(Integer.toString(sum));
// for subtraction
int sub = 0;
if(num1_error == 0){
sub = num1 - sub;
}
if(num2_error == 0){
sub = sub - num2;
}
if(num3_error == 0){
sub = sub - num3;
}
t1.setText(Integer.toString(sub));
// for multiplication
int mul = 1;
if(num1_error == 0){
mul = mul*num1;
}
if(num2_error == 0){
mul = mul*num2;
}
if(num3_error == 0){
mul = mul*num3;
}
t1.setText(Integer.toString(mul));
Try doing this and same for other methods:
EditText e1 ,e2, e3;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.editText);
e2 = (EditText)findViewById(R.id.editText2);
e3 = (EditText)findViewById(R.id.editText3);
t1 = (TextView)findViewById(R.id.textView2);
}
public void onButtonClickSum(View v){
if(e1.getText().toString().length()==0){
e1.setError("Required");
}
else if(e2.getText().toString().length()==0){
e2.setError("Required");
}
else if(e3.getText().toString().length()==0){
e3.setError("Required");
}
else{
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sum = num1 + num2 + num3;
t1.setText(Integer.toString(sum));
}
}

CalculateButton in BMI calculator

it's me again... I want to ask how to make my "button" (calculateButton) not to function if the user won't input their weight & height... or the user don't input their weight or their height... Hope you can help me... thanks..
Here is the code for my calculateButton:
public void calculateClickHandler(View view) {
if (view.getId() == R.id.calculateButton) {
}
EditText weightText = (EditText) findViewById(R.id.weightT);
EditText heightText = (EditText)findViewById(R.id.heightT);
TextView resultText = (TextView)findViewById(R.id.resultLabel);
TextView categoryText = (TextView)findViewById(R.id.categoryLabel);
rGroup = (RadioGroup)findViewById(R.id.rGroup);
int weight = (int) Float.parseFloat(weightText.getText().toString());
int height = (int) Float.parseFloat(heightText.getText().toString());
int bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
resultText.setText("Your BMI is:" + " " + bmiValue + " " + "and you're");
categoryText.setText(bmiInterpretation + ".");}
You need to insert "validations" in your code. Basically checking the value of the string in your EditText before performing any operation.
Something like:
rGroup = (RadioGroup)findViewById(R.id.rGroup);
if( !weightText.getText().toString.equals(" ")){
int weight = (int) Float.parseFloat(weightText.getText().toString());
int height = (int) Float.parseFloat(heightText.getText().toString());
int bmiValue = calculateBMI(weight, height);
}
Refer:
Android, Validate an empty EditText field
https://sites.google.com/site/khetiyachintan/sample-example/edit-text-validation-example
Android EditText validation

Categories

Resources