Search code examples
androidcodenameonebarcode

Codename One - scanning barcodes checking for new line/ENTER character


in Android I can easily detect the ENTER character using the setOnEditorActionListener method so that when a barcode is scanned into a textfield I know when the whole barcode has been read.

[Here is the Android code as requested:]

scanEditText.setOnEditorActionListener(new TextView.OnEditorActionListener()
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            if ( (actionId == EditorInfo.IME_ACTION_DONE) || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN )))
            {
                System.out.println("   *** ENTER!");
                return true;
            }
            else
                return false;
        }
    });

I have been trying to replicate this in Codename One but with no luck. I have tried

  • setDoneListener
  • addDataChangedListener
  • ActionEvent on the text field and text area
  • overriding the keyPressed and keyReleased methods

but with no joy. If I set a textField with setSingleLineTextArea(false) I can see the barcode characters appear in the box followed by what I am assuming is a new line character as the next scan appears on a new line. None of the methods listed seem to catch this event. If I change the focus to another box the ActionEvent is triggered but I don't want to have to move the focus each time.

[Here is the Codenameone code]

gui_searchTextField.setSingleLineTextArea(false);
gui_searchTextField.setDoneListener(new ActionListener()
{
     public void actionPerformed(ActionEvent evt)
     {
        Dialog.show("KB", "doneListener " + 
        gui_searchTextField.getText().trim(), "OK", null);
     }
});
gui_searchTextField.addDataChangedListener((evt1, evt2) ->
{
  System.out.println("DataChanged " + gui_searchTextField.getText());
});

So, how do I catch the end of the barcode like I can easily in the Android SDK?


Solution

  • Text input is very much a special case for us in all OS's so the keys go directly into the native OS text editing and don't "travel" through Codename One API's. However, DataChangeListener should be invoked for every key input so I'm not sure how this is happening exactly.

    I did notice you are using System.out instead of Log.p so you might miss the output from the device related to the changes. Also I would recommend overriding the key pressed/released events and not starting the text editing. Then adding the key value to the text field instead of letting the native input handle it e.g.:

    class MyForm extends Form {
        public void keyReleased(int key) {
            if(isCrLf(key)) {
                // do this...
            } else {
                myTextField.setText(myTextField.getText() + ((char)key));
            }
        }
    }