How can I find out when the value in the TextField has been changed?
Article Metadata
Code Example
Source file: Media:TextFieldItemStateListenerMIDlet.zip
Article
Created: arunjyothiskp
(21 Nov 2007)
Last edited: hamishwillee
(05 Jul 2012)
When working with TextField items, it is often useful to be automatically notified when the TextField content changes (e.g.: to implement an autocomplete field, or some sort of automated filter for a list of other Items).
Source code
You must use the ItemStateListener interface and register the listener to the form. The easiest way is to implement ItemStateListener on the form that contains your TextField and put your code into the itemStateChanged method.
class MyClass extends Form implements ItemStateListener
{
public MyClass()
{
setItemStateListener(this);
}
public void itemStateChanged(Item item)
{
...
}
}
Another approach would be to create an anonymous class and register it with the form:
public class MyClass extends MIDlet
{
public void startApp()
{
Form form = new Form("My Test");
// an anonymous class
ItemStateListener listener = new ItemStateListener()
{
public void itemStateChanged(Item item)
{
// do something
}
};
// register for events
form.setItemStateListener(listener);
...
display.setCurrent(form);
}
}
Download
You can download a MIDlet showing the code presented in this article here: Media:TextFieldItemStateListenerMIDlet.zip


25 Sep
2009
This is a fairly basic article which demonstrates how to listen for changes to Item instances contained in a Form. As the article points out, this can be useful in order to implement functionality such as auto-complete, where the list of options needs to be updated in response to users entering text in a Form component such as a TextField.
A simple code example is provided which does a good job of demonstrating how to implement the ItemStateListener interface (and the itemStateChanged method). It also shows how to set the ItemStateListener for a form. Usefully, a link is also provided to download a midlet which demonstrates the use of an ItemStateListener implementation in an actual application.