-3

I'm new in Android development and was trying to make an app with the below code, but once I press the "Score" button, the app crashes. I tried to add a Toast message under the OnClick method for the "Score" button to prevent that, but it seems that I can't retrieve int and String from the same EditText under the onClick method (it keeps closing the app when i do so). The below codes were tried but with no luck. So, can anyone help me with the proper code to prevent the app from crashing when the EditText is blank? I tried the below test code but the problem still the same.

displayScore1.getText().toString().equals("")
displayScore1.getText().toString().matches("")
displayScore1.getText().length() != 0

package com.example.android.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    int score1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button test = (Button)findViewById(R.id.button);
        test.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                EditText displayScore1 = (EditText) findViewById(R.id.score);
                score1 = Integer.parseInt(displayScore1.getText().toString());

                if (!displayScore1.getText().toString().trim().isEmpty()){
                    displayText(score1);
                }
                else{
                    Toast.makeText(MainActivity.this, "Please enter the Number of Tricks", Toast.LENGTH_SHORT).show();
                }
            }
            });
    }

    public void displayText(int message){
        TextView display = (TextView)findViewById(R.id.text);
        display.setText("" + message);
    }


}

2 Answers2

1

You can use any approach but need be aware of with spaces and new lines. One example is shown below.

if(!displayScore1.getText().toString().trim().isEmpty()){
// edittext has some thing
}else{
//do what you want to do when edittext is empty
}
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49
  • Unfortunately, it didn't work. I pasted above a test code that i used to demonstrate what i am doing. Please let me know if i'm missing something in the syntax. – user7440913 Feb 03 '17 at 14:19
0

Try like this

 displayScore1.getText().toString().trim().length()==0{
//your code

}
Rajakumar
  • 907
  • 1
  • 7
  • 17
  • Didn't work :( Is it because i can't extract two different values from the same view under the onClick? because if i turn the method to get only String, it works fine. But the thing is, the main type i'm targeting out of this Edittext is Int. – user7440913 Feb 03 '17 at 18:38