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);
}
}