IF condition is true but does not execute related code

Asked

Viewed 477 times

3

I have my program that displays a message and in that same message the user must enter a code. I’m trying to validate whether he typed something or not, so I use the code:

AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle("Código final"); //Set Alert dialog title here
    alert.setMessage("Insira o código fornecido pela Nobre de la Torre:"); //Message here

    // Set an EditText view to get user input 
    final EditText input = new EditText(context);
    alert.setView(input);

    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
     //Ações do botão da mensagem
     String srt = String.valueOf(input.getEditableText());
     if(srt!=""){ //ESSE É O IF QUE ESTÁ COM ERRO
     Toast.makeText(context,srt,Toast.LENGTH_LONG).show();  
     }
     else
     {
     Toast.makeText(context,"Campo vazio!",Toast.LENGTH_LONG).show();  
     }  
      String hexNumber = srt;
      int decimal = Integer.parseInt(hexNumber, 16);
      System.out.println("Hex value is " + decimal); 
                 [COntinua...]

Even with the variable String srt being "" he sees as different from "" and execute the code below it

String srt = String.valueOf(input.getEditableText());
if(srt!=""){ 
    Toast.makeText(context,srt,Toast.LENGTH_LONG).show();
}

Since he should execute the else :

else {
    Toast.makeText(context,"Campo vazio!",Toast.LENGTH_LONG).show();}
  • 1

    http://answall.com/questions/3905/como-comparar-strings-em-java

1 answer

3

Modify for this implementation

String srt =input.getText().toString();
if(!srt.equals(""))

The method getEditableText() class EditText returns an object of type Editable, to pick up the text you must use the method getText() which returns an object of the type CharSequence, soon after just convert it to String.

  • put as the following: String srt =input.getText().toString();
 if(srt.equals(""))
 {
 Toast.makeText(context,"Campo vazio!",Toast.LENGTH_LONG).show(); 
 }
 else
 {
 Toast.makeText(context,srt,Toast.LENGTH_LONG).show(); 
 } And now stopped the application gave error.

  • What mistake? @kaamis

  • Just an addendum, I put a denial in the if because I realized that the condition is different from Right Void.

  • Your answer of a certain @Tuyoshivinicius even without the negation. The mistake I believe is for the continuity of the code. When leaving the if there is a variable String which receives the value of srt. If it is empty it gives error in the continuity of the code. You would have to enter the if and verify that srt it is empty to have the possibility to execute the condition code and stop there. Not to continue the code until srt is different from empty.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.