1. Are you ready for the Galaxy S20? Here is everything we know so far!

App crashes on button click with empty edittext

Discussion in 'Android Development' started by Predrag Antić, Jun 28, 2017.

  1. Predrag Antić

    Thread Starter

    I'm working on an application with some mathematical problems. I made a photo in the photoshop and under the image there is an editText and button. Everything is fine, but when I click the button when editText is empty the application crashes. I tried some solutions, but they did not help me. So if can anyone help me i would be grateful. :)

    Code (Text):
    1. public class Start1Activity extends AppCompatActivity {
    2.  
    3.     Button btn;
    4.  
    5.     public void displayResult(String result) {
    6.         Toast.makeText(Start1Activity.this, result, Toast.LENGTH_SHORT).show();
    7.     }
    8.  
    9.     public void guess(View view){
    10.         final EditText EditText2 = (EditText) findViewById(R.id.editText2);
    11.  
    12.         final int guessNumber = Integer.parseInt(EditText2.getText().toString());
    13.  
    14.         if (guessNumber == 3 ){
    15.             displayResult("That's right! Click once again for next level");
    16.             btn = (Button) findViewById(R.id.bt3);
    17.             btn.setOnClickListener(new View.OnClickListener(){
    18.                 @Override
    19.                 public void onClick(View view){
    20.                     if(EditText2.getText().toString().isEmpty()){
    21.                         displayResult("Please enter some number");
    22.                     }
    23.                     Intent anythingintent=new Intent(Start1Activity.this,Start2Activity.class);
    24.                     startActivity(anythingintent);
    25.                 }
    26.             });
    27.         }
    28.         else{
    29.             displayResult("Wrong. Try again!");
    30.  
    31.         }
    32.     }
    33.  
    34.  
    35.     @Override
    36.     protected void onCreate(Bundle savedInstanceState) {
    37.         super.onCreate(savedInstanceState);
    38.         setContentView(R.layout.activity_start1);
    39.     }
    40. }
     


  2. Best Answer:
    Post #2 by Deleted User, Jun 28, 2017 (3 points)

    1. Download the Forums for Android™ app!


      Download

       
  3. Deleted User

    Deleted User Guest

    I'm guessing that getText() returns null and you got a NullPointerException

    Code (Text):
    1.  
    2. if(EditText2.getText().toString().isEmpty()){
    3.  
    So replace the above line with

    Code (Text):
    1.  
    2. if (EditText2.getText() == null || EditText2.getText().equals("")) {
    3.  
     
  4. wseng92

    wseng92 Android Enthusiast

    If app crashed, please post the stack trace.
     
Loading...

Share This Page

Loading...