Search code examples
androidandroid-edittextandroid-textwatcher

getting edittext.settext data from textwatcher in android


I am setting the text in EditText but when getting the text from TextWatcher it is giving empty string.

Please check this code

for (int i = 0; i < 4; i++) {
   et = new EditText(this);
   et.setText("hai");
   final EditText finalEt = et;
   ans.addView(et);
   final int finalI = i;
   finalEt.addTextChangedListener(new TextWatcher() {
       public void afterTextChanged(Editable s) {
           Log.d("text is",""+finalEt.getText().toString());
       }

       public void beforeTextChanged(CharSequence s, int start,int count, int after) {}

       public void onTextChanged(CharSequence s, int start,int before, int count) {}
   }

Solution

  • You will get it in onTextChanged as well as on afterTextChanged something like this.

    for (int i = 0; i < 4; i++) {
    et = new EditText(this);
    et.setText("hai");
    
    final EditText finalEt = et;
    
    ans.addView(et);
    final int finalI = i;
    finalEt.addTextChangedListener(new TextWatcher() {
       public void afterTextChanged(Editable s) {
                       String str = s.toString();
               Log.d("text is",""+s);
    
       }
    
       public void beforeTextChanged(CharSequence s, int start,int count, int after) {}
    
       public void onTextChanged(CharSequence s, int start,int before, int count) {
               Log.d("text is",""+s.toString());
       }
    }