-1

This is a snippet of my MainActivity.java.

@Override
                public void onClick(View v) {
                    EditText textField = findViewById(R.id.messageField);
                    if (!(textField.getText().toString() != "")){
    
                    FirebaseDatabase.getInstance().getReference().push().setValue(
                            new Message(FirebaseAuth.getInstance().getCurrentUser().getEmail(), textField.getText().toString()));
                    textField.setText(""); }
        }
ADM
  • 20,406
  • 11
  • 52
  • 83
MakarMS
  • 25
  • 4

2 Answers2

1

Updated Code

 @Override
  public void onClick(View v) {
    EditText textField = findViewById(R.id.messageField);
    if (!(textField.getText().toString().equalsIgnoreCase(""))) {

        FirebaseDatabase.getInstance().getReference().push().setValue(
                new Message(FirebaseAuth.getInstance().getCurrentUser().getEmail(), textField.getText().toString()));
        textField.setText("");
    }
}

Here is the solution.

Sanwal Singh
  • 1,765
  • 3
  • 17
  • 35
  • One should not compare strings with `==` or `!=` in java – Ackdari Sep 01 '20 at 11:04
  • @Ackdari, sorry for this, I had change the answer and replace it with equalsIgnoreCase() – Sanwal Singh Sep 01 '20 at 11:08
  • 1
    This will fail if `textField.getText()` returns null or if `textField` itself is null. When comparing to constant string values and variables you should invoke the comparison method on the constant string value, not on the variable. – JustAnotherDeveloper Sep 01 '20 at 11:20
1

Don't compare strings using operators like == or !=. if (!(textField.getText().toString() != "")){ should be if ("".equals(textField.getText().toString())){

Note that I've reversed the order of comparison, I'm comparing the empty string to the content of the text field. This is because your text field could be null, or the getText() method could return null. In those cases, calling equals() would return a NullPointerException. When comparing a string constant value to a variable, you should call the comparison method on the constant value to avoid this problem, as the constant will, by definition, never be null.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24
  • You may want to add explanation why, this is the correct and better way to compare a variable string to a constant string value. But this should be the accepted answer nonetheless. – Ackdari Sep 01 '20 at 12:33
  • Good point. I did something like that in a comment in the incorrect accepted answer, might as well bring it over to my answer to improve it. Give me a minute to edit it. – JustAnotherDeveloper Sep 01 '20 at 12:53