Home > Software engineering >  Fix app keep stopping made with android studio
Fix app keep stopping made with android studio

Time:09-21

I'm new on android development field. Last night I made a simple calculator from a youtube tutorial and fortunately I've successfully made it. Here is the code

main.xml:-

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top|center">

    <ImageView
        android:layout_height="120dp"
        android:layout_width="120dp"
        android:src="@drawable/cal"/>

    <EditText
        android:layout_width="wrap_content"
        android:inputType="number"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:hint="@string/fstval"
        android:id="@ id/etFirstValue"/>

    <EditText
        android:layout_width="wrap_content"
        android:inputType="number"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:hint="@string/sndval"
        android:id="@ id/etSecondValue"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:hint="@string/ans"
        android:textColorHint="#FF0F00"
        android:id="@ id/tvAns"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:layout_marginTop="19dp"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:background="#4C5866"
        android:padding="10dp"
        android:textColor="#000000"
        android:textSize="25sp"
        android:id="@ id/btnAdd"
        android:onClick="btnadd"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/sub"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:background="#677789"
        android:padding="10dp"
        android:layout_marginTop="5dp"
        android:textColor="#000000"
        android:textSize="25sp"
        android:id="@ id/btnSubtract"
        android:onClick="btnsub"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/mul"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:background="#405163"
        android:padding="10dp"
        android:layout_marginTop="5dp"
        android:textColor="#000000"
        android:textSize="25sp"
        android:id="@ id/btnMultiply"
        android:onClick="btnmul"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/div"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:background="#19E6B1"
        android:padding="10dp"
        android:layout_marginTop="5dp"
        android:textColor="#000000"
        android:id="@ id/btnDivide"
        android:textSize="25sp"
        android:onClick="btndiv"/>

    

</LinearLayout>

mainactivity.java:-

    package com.mycompany.myapp;

import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.View.*;
import android.view.*;

public class MainActivity extends Activity 
{
    
    
    private EditText etn1;  
    private EditText etn2;
    private TextView tvResult;
    private Button btnadd , btnsub , btnmul , btndiv;
    
    
    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        etn1 = findViewById(R.id.etFirstValue);
        etn2 = findViewById(R.id.etSecondValue);
        tvResult = findViewById(R.id.tvAns);
        
        
        Button btnadd = findViewById(R.id.btnAdd);  
        btnadd.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    
                    int n1 = Integer.parseInt(etn1.getText().toString());
                    int n2 = Integer.parseInt(etn2.getText().toString());

                    int add = n1   n2;

                    tvResult.setText(String.valueOf(add));
                }
            
        
            
        });
        
        Button btnsub = findViewById(R.id.btnSubtract);  
        btnsub.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    int n1 = Integer.parseInt(etn1.getText().toString());
                    int n2 = Integer.parseInt(etn2.getText().toString());

                    int add = n1 - n2;

                    tvResult.setText(String.valueOf(add));
                }



            });
        Button btnmul = findViewById(R.id.btnMultiply);  
        btnmul.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    int n1 = Integer.parseInt(etn1.getText().toString());
                    int n2 = Integer.parseInt(etn2.getText().toString());

                    int add = n1 * n2;

                    tvResult.setText(String.valueOf(add));
                }



            });
        Button btndiv = findViewById(R.id.btnDivide);  
        btndiv.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    int n1 = Integer.parseInt(etn1.getText().toString());
                    int n2 = Integer.parseInt(etn2.getText().toString());

                    int add = n1 / n2;

                    tvResult.setText(String.valueOf(add));
                }



            });
        
        
        
    

            
        
        

    }

}

But the problem is when I don't put any value into the firstEditText or secondEditText or both of them and click on any button the app got crash and a pop up showing "myapp keeps stopping". I want something like " Please enter a value" shows on the blank EditText when I don't pun any value to any of EditText. Help me please

CodePudding user response:

The problem is your input (say, etn1.getText().toString()) may not be a number. So you get NumberFormatException. To fix this, rewrite your code like this:

btnadd.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
int n1 = 0;
int n2 = 0;
try{
  n1 = Integer.parseInt(etn1.getText().toString());
}catch(Exception x) { 
  x.printStackTrace(); 
  n1 = 0;
}

try{
   n2 = Integer.parseInt(etn2.getText().toString());
}catch(Exception x) { 
  x.printStackTrace(); 
  n2 = 0;
}
 
                    int add = n1   n2;

                    tvResult.setText(String.valueOf(add));
                }
            
        
            
        });

CodePudding user response:

You're receiving a NumberFormatException because when you run

Integer.parseInt(etn1.getText().toString())

When a EditText field has no value it returns "". "" cannot be transcribed into a number. Therefore, it throws the NumberFormat Exception.

There are a number of ways to handle this but i would suggest using Uncle Bobs Clean Code methodology. You can encapsulate your within a try catch block for each button click like so:

try{
  n1 = Integer.parseInt(etn1.getText().toString());
}catch(NumberFormatException x) { 
  x.printStackTrace(); 
  n1 = 0;
}

But i would suggest that given this code will have multiple uses across all button types, you move your n variables to global variables (at the top of the code base i.e int n1) and produce a new method such as

Private void setNumbers(){
try{
      n1 = Integer.parseInt(etn1.getText().toString());
      n2 = Integer.parseInt(etn2.getText().toString());
    }catch(NumberFormatException x) { 
      x.printStackTrace(); 
      n1 = 0;
      n2 = 0;
    }
}

Then within each Button onClick Listener could look like:

btndiv.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                setNumbers();
                int divide = n1 / n2;
                tvResult.setText(String.valueOf(divide));
                } 
            });
    

CodePudding user response:

Your app is crashing because when you don't enter any value and tap on buttons, it tries to parse an empty string to int which leads to a NumberFormatException and crashes your app. However, you can first check if your edit texts are empty or not before parsing them, and show a toast or a snackbar if they are empty.

Use this

 String number1 = etn1.getText().toString();
 String number2 = etn2.getText().toString();
 if(number1.isBlank() || number2.isBlank()){
     Toast.makeText(this, "Please enter a value", Toast.LENGTH_LONG).show();
} else {

 int n1 = Integer.parseInt(number1);
 int n2 = Integer.parseInt(number2);

 int add = n1   n2;

 tvResult.setText(String.valueOf(add));
}
  • Related