Search code examples
androidbarcodeandroid-edittextbarcode-scanner

EditText, OnKeyListener or TextWatcher (barcode scanning)


I'm using a barcode scanner which inserts barcode string into an EditText in this format "12345\n". Instead of using a search button, I want to trigger the search event by the "\n" character. I used TextEdit's addTextChangedListener and inside that function I'm doing:

protected TextWatcher readBarcode = new TextWatcher() { 
 @Override
 public void onTextChanged(CharSequence s, int start, int before, int count) {
  // TODO Auto-generated method stub

 }

 @Override
 public void beforeTextChanged(CharSequence s, int start, int count,
   int after) {
  // TODO Auto-generated method stub

 }

 @Override
 public void afterTextChanged(Editable s) {
  // TODO Auto-generated method stub
  char lastCharacter = s.charAt(s.length() - 1);

  if (lastCharacter == '\n') {
   String barcode = s.subSequence(0, s.length() - 1).toString();
   searchBarcode(barcode);
  }
 }
};

It works pretty good for the first time, but I also want to clear the EditText after each scan. But it's not possible to do that inside afterTextChanged event because it's going into a recursive loop or something.

Here is the other solution, which is working pretty good:

editBarcode.setOnKeyListener(new OnKeyListener() {

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    String barcode = editBarcode.getText().toString();

    if (keyCode == KeyEvent.KEYCODE_ENTER && barcode.length() > 0) {
        editBarcode.setText("");
        searchBarcode(barcode);
        return true;
    }

    return false;
}
});

Actually I'm not sure what is the right way to do it it. Maybe I can use EditText's OnKeyListener event. Any suggestions?

Thanks


Solution

  • If you clear the EditText content in the afterTextChanged(), you shouldn't have an infinite loop.

     @Override 
     public void afterTextChanged(Editable s) { 
      if (s.length > 0) {
    
          char lastCharacter = s.charAt(s.length() - 1); 
    
          if (lastCharacter == '\n') { 
           String barcode = s.subSequence(0, s.length() - 1).toString();
           myEditText.setString("");
           searchBarcode(barcode); 
          }
      }