CYB
CYB

Reputation: 1106

Edittext getText toString

Below is my EditText and I want to put it input a String tel The Toast will succeed to show the getText toString However, I didn't see the value put into tel in LogCat.

     edittext = (EditText) findViewById(R.id.editTel);
     edittext.setOnEditorActionListener(new OnEditorActionListener() {  
         @Override  
         public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
            Toast.makeText(Reserve.this, edittext.getText().toString(), Toast.LENGTH_SHORT).show();  
            tel = edittext.getText().toString();
             return true;  
         }  
     });

     Log.d("TEL", "The tel is: "+tel);

Upvotes: 0

Views: 1527

Answers (2)

Jorge
Jorge

Reputation: 487

You are just calling a method that stores a reference to an object (of the OnEditorActionListener class) inside the EditText object. The flow continues immediately executing the Log.d() method, printing and empty ¨tel¨. The OnEditorActionListener.onEditorAction() method will be called anytime else, triggered by a user action, and it will execute the code inside it. Maybe the flow could be clearer written like this:


OnEditorActionListener listener = new OnEditorActionListener() {  
         @Override  
         public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
            Toast.makeText(Reserve.this, edittext.getText().toString(), Toast.LENGTH_SHORT).show();  
            tel = edittext.getText().toString();
             return true;  
         }  
     });

edittext = (EditText) findViewById(R.id.editTel);
edittext.setOnEditorActionListener(listener);
Log.d("TEL", "The tel is: "+tel);

This way is clearer that the onEditorAction() method is completely independent from the normal flow of execution of that piece of code.

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

put Log.d("TEL", "The tel is: "+tel); inside onEditorAction method as:

@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Toast.makeText(Reserve.this, edittext.getText().toString(),
                                 Toast.LENGTH_SHORT).show();
tel = edittext.getText().toString(); 
Log.d("TEL", "The tel is: "+tel);
return true;
}
});

because maybe possible control is not reached outside OnEditorActionListener

Upvotes: 3

Related Questions