×

Discussion Board

Results 1 to 15 of 15
  1. #1
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Need help with an ItemStateListener.

    I am trying to use an ItemStateListener to determine what choice in a choice group is selected.

    On the main screen, four choices are displayed:
    (Add a choice)
    Choice 1
    Choice 2
    Choice 3
    Clicking on the "Go" button displays a new screen with some test information. The information includes the word "Testing", an index number from the aforementioned choice group, a string associated with that index number from the choice group, and a text field. When at the main screen, no matter which choice I select, when I click on the "Go" button, the next screen always displays the below:
    Testing
    0
    (Add a choice)
    New choice to add
    [____________________________]
    (That last item above represents the text field.)

    Also, for testing purposes, there is "System.out.println" code to indicate a state change involving the clicking on a choice in the choice group. When I click on a choice in the choice group, the console does not produce any "System.out.println" output but instead directs my attention to this line of code:

    Code:
    intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    The full code is below:

    Code:
    //
    //  ChoiceGroupOptionActionTest.java
    //  
    //
    //
    
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.util.*;
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.rms.*;
    import java.lang.*;
    
    public class ChoiceGroupOptionActionTest extends MIDlet implements CommandListener, ItemStateListener {
    
    	private RecordStore choicesTestDb = null;
    	private Command exitCommand, goCommand, saveCommand, cancelCommand;
    	private Display display;
    	private Form screen;
    	private Form frmAddChoice;
    	private Alert alert;
    	private int i, intNumberOfRecords, intSelectedIndex;
    	private StringBuffer strbBuffer;
    	private ChoiceGroup cgChoices;
    	private ChoiceGroup cgDefaultChoices;
    	private String strSelectedIndex, strSelectedChoice, strSelectedChoiceForStateChange;
    	
    	public ChoiceGroupOptionActionTest() {
    		// Get the display object for the MIDlet.
    		display = Display.getDisplay(this);
    
    		// Create the Exit and Go commands.
    		exitCommand = new Command("Exit", Command.EXIT, 2);
    		goCommand = new Command("Go", Command.OK, 2);
    		saveCommand = new Command("Save", Command.OK, 2);
    		cancelCommand = new Command("Cancel", Command.CANCEL, 2);
    
    		// Create the screen form.
    		screen = new Form("Main Screen");
    
    		// Set the Exit and Go commands for the screen.
    		screen.addCommand(exitCommand);
    		screen.addCommand(goCommand);
    		screen.setCommandListener(this);
    		screen.setItemStateListener(this);
    	}
    
    	//public void startApp() throws MIDletStateChangeException {
    	public void startApp() {
    	
    		// Open the record store.
    		try {
    		choicesTestDb = RecordStore.openRecordStore("choicestestfile", true);
    		} catch (RecordStoreNotFoundException rsnfe) {
    		// Handle the exception.
    		} catch (RecordStoreFullException fsfe) {
    		// Handle the exception.
    		} catch (RecordStoreException rse) {
    		// Handle the exception.
    		}
    
    		// If the record store has no records yet, write to it.
    		try {
    			intNumberOfRecords = choicesTestDb.getNumRecords();
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    		if (intNumberOfRecords == 0) {
    			writeRecordToChoicesRecordStore("Choice 1");
    			writeRecordToChoicesRecordStore("Choice 2");
    			writeRecordToChoicesRecordStore("Choice 3");
    		}
    	
    			String[] strDefaultChoices = { "(Add a choice)" };
    			ChoiceGroup cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    			
    			/*
    			// Empty the choice group before enumerating the record store.
    			for (int j = cgDefaultChoices.size(); j > 0; j--) {
    				cgDefaultChoices.delete(j - 1);
    			}
    			*/
    
    
    		// Read from the choices test record store and display to the screen.
    		String strTheChoice = null;
    		try{
    			if (choicesTestDb.getNumRecords() > 0) {
    				//Comparator comp = new Comparator();
    				//RecordEnumeration reChoicesTestEnumeration = choicesTestDb.enumerateRecords(null, comp, false);
    				RecordEnumeration reChoicesTestEnumeration = choicesTestDb.enumerateRecords(null, null, false);
    
    				while (reChoicesTestEnumeration.hasNextElement()) {
    				//String strTheChoice = new String(reChoicesTestEnumeration.nextRecord());
    				try {
    					strTheChoice = new String(reChoicesTestEnumeration.nextRecord());
    				} catch (RecordStoreException ex) {
    					ex.printStackTrace();
    				}
    				cgDefaultChoices.append(strTheChoice, null);
    				//System.out.println("------------------------------"); // This can be uncommented for testing purposes.
    				//System.out.println(strTheChoice);                   // This can be uncommented for testing purposes.
    				//System.out.println("------------------------------"); // This can be uncommented for testing purposes.
    				}
    			}
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    
    		screen.append(cgDefaultChoices);
    	
    		int intSelectedChoice = cgDefaultChoices.getSelectedIndex();
    		//int indexSelected = cgDefaultChoices.getSelectedIndex();///////////////////////////////////////
    		strSelectedIndex = Integer.toString(intSelectedChoice);
    		strSelectedChoice = cgDefaultChoices.getString(intSelectedChoice);
    		
    		// Set the current display to the screen.
    		display.setCurrent(screen);
    	
    		// Close the record store.
    		try {
    			choicesTestDb.closeRecordStore();
    		}
    		catch (Exception error) {
    			alert = new Alert("Error Closing", 
    				error.toString(), null, AlertType.WARNING); 
    			alert.setTimeout(Alert.FOREVER); 
    			display.setCurrent(alert);
    		}
    
    	}
    
    	public void pauseApp() {
    	}
    
    	public void destroyApp(boolean unconditional) {
    	}
    
    
    	public void goCom() {
    	
    		// Create the add choice form.
    		frmAddChoice = new Form("Add Choice");
    
    		// Set the Exit and Save commands for the add choice form.
    		frmAddChoice.addCommand(cancelCommand);
    		frmAddChoice.addCommand(saveCommand);
    		frmAddChoice.setCommandListener(this);
    
    		// Add a text field for entering the new choice.
    		frmAddChoice.append(new StringItem("", "Testing\n"));//////////////////////////////////////////////////////////////////
    		frmAddChoice.append(new StringItem("", strSelectedIndex + "\n"));//////////////////////////////////////////////////////////////////
    		frmAddChoice.append(new StringItem("", strSelectedChoice));//////////////////////////////////////////////////////////////////
    		TextField addChoiceField = new TextField("New choice to add", "", 40, TextField.ANY);
    		frmAddChoice.append(addChoiceField);
    	
    		// Set the current display to the add choice form.
    		display.setCurrent(frmAddChoice);
    	}
    
    	public void cancelCom() {
    		display.setCurrent(screen);
    	}
    
    	public void commandAction(Command c, Displayable s) {
    		if (c == exitCommand) {
    			destroyApp(false);
    			notifyDestroyed();
    		} else if (c == goCommand) {
    			goCom();
    		} else if (c == cancelCommand) {
    			cancelCom();
    		}
    	}
    
    	public void itemStateChanged(Item item) {
    		intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    		strSelectedChoiceForStateChange = cgDefaultChoices.getString(intSelectedIndex);
    		System.out.println("Inside itemStateChanged() to choice group index number " + intSelectedIndex + " (" + strSelectedChoiceForStateChange + ")");
    	}
    
    	public void writeRecordToChoicesRecordStore(String strRecord) {
    		byte[] bytesRecord = strRecord.getBytes();
    		try {
    			choicesTestDb.addRecord(bytesRecord, 0, bytesRecord.length);
    		} catch (RecordStoreException e) {
    				e.printStackTrace();
    		}
    	}
    
    }
    Any help regarding this matter would be greatly appreciated.

  2. #2
    Nokia Developer Expert
    Join Date
    Aug 2011
    Posts
    555

    Re: Need help with an ItemStateListener.

    Inside your startApp() method

    replace line:
    Code:
    ChoiceGroup cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    with:

    Code:
    cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    that should solve your issue. Please be aware that when you define a variable with the same name both in local scope and as a class variable, and you give a value to your local variable, the class variable still remains undefined.

    That is a problem specially when you try to access the variable from another method, as the local variable is no longer visible and the class variable is undefined.

  3. #3
    Nokia Developer Champion
    Join Date
    Feb 2009
    Location
    Noida, India
    Posts
    3,087

    Re: Need help with an ItemStateListener.

    Also Try with List.IMPLICIT in place of List.EXCLUSIVE
    thanks,
    ~Amitabh
    (Champion of the Month -Aug'13)
    Follow me on my blog for Innovative Mobile Apps

  4. #4
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    Thank you, skalogir and im2amit.

    After the change of this:

    Code:
    ChoiceGroup cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    to this:

    Code:
    cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    …clicking on a choice in the choice group now results in the console producing "System.out.println" output.

    When clicking on the "Go" button after selecting any of the choices in the choice group, the display on the second screen continues to be:

    Testing
    0
    (Add a choice)
    New choice to add
    [____________________________]
    I plan to try some more tests in that regard.
    Last edited by John_123; 2011-10-18 at 16:16.

  5. #5
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    Below this line of code:

    Code:
    screen.append(cgDefaultChoices);
    I added this line of code:

    Code:
    cgDefaultChoices.setSelectedIndex(3, true);
    After that change, clicking on the "Go" button results in the second screen displaying the following:

    Testing
    3
    Choice 3
    New choice to add
    [____________________________]
    I plan to continue the investigation of this matter.

  6. #6
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    I added some more code. Below is an excerpt:

    Code:
    	public void itemStateChanged(Item item) {
    	
    		if (item == cgDefaultChoices) {
    			intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    			//if (intSelectedIndex == null) {
    			//	intSelectedIndex = 3;
    			//}
    			strSelectedChoiceForStateChange = cgDefaultChoices.getString(intSelectedIndex);
    			System.out.println("Inside itemStateChanged() to choice group index number " + intSelectedIndex + " (" + strSelectedChoiceForStateChange + ")");			
    			// Display the add form screen along with some testing info.
    			strSelectedIndex = Integer.toString(intSelectedIndex);
    			strSelectedChoice = cgDefaultChoices.getString(intSelectedIndex);
    		}
    	}
    Now, if I select a choice in the choice group, when I click on the "Go" button, the information related to that particular choice is displayed on the second screen; however, if I do not click on any of the choices, the information related to the default choice is not displayed. Instead, the word "null" is displayed. I tried using an if-statement to take care of the situation with the null value, but that didn't work; therefore I commented out that section of code.

    I plan to explore this further.

  7. #7
    Nokia Developer Expert
    Join Date
    Aug 2011
    Posts
    555

    Re: Need help with an ItemStateListener.

    Hi John,

    My understanding (correct me if I am wrong), is that you are trying to display the selected choice on the "Add Choice" Screen. So if I select Choice 1 from the Main Screen and press GO, I should see Testing 1, but if I select Choice 2 and then select Go, the next screen should display Testing 2 and so one.

    If that's what you are trying to do, the problem is again a variable issue. You are storing the selected choice in this variable:
    intSelectedIndex
    but when you are displaying the "Add Choice" screen you retrieve the contents of the strSelectedIndex variable. You need to change this line:
    Code:
    frmAddChoice.append(new StringItem("", strSelectedIndex + "\n"));
    with this:
    Code:
    frmAddChoice.append(new StringItem("", cgDefaultChoices.size()-intSelectedIndex + "\n"));

  8. #8
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    Thank you, skalogir. You understand correctly. I'll make the changes that you recommended and check back here.

  9. #9
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    (I have divided my update into three message posts because there would be too many characters to post them combined together.) The first of the three posts has the code from the 4th version of the MIDlet. The 4th version shows what I had been trying to accomplish. When the "Go" button is clicked, it displays some information for testing purposes. Also, the text field labeled "New choice to add" only appears if "(Add a choice)" is selected. Below is the code for that 4th version:

    Code:
    //
    //  ChoiceGroupOptionActionTest4.java
    //  
    //
    //
    /* This code reflects content in the discussion thread at the below web page:
    http://www.developer.nokia.com/Community/Discussion/showthread.php?229634-Need-help-with-an-ItemStateListener.&p=864423#post864423
    */
    // This version 4 differs from version 3 in that the text field on the add form screen only appears if "(Add a choice)" is selected.
    
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.util.*;
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.rms.*;
    import java.lang.*;
    
    public class ChoiceGroupOptionActionTest4 extends MIDlet implements CommandListener, ItemStateListener {
    
    	private RecordStore choicesTestDb = null;
    	private Command exitCommand, goCommand, saveCommand, cancelCommand, addCommand;
    	private Display display;
    	private Form screen;
    	private Form frmAddChoice;
    	private Alert alert;
    	private int i, intNumberOfRecords, intSelectedIndex;
    	private StringBuffer strbBuffer;
    	private ChoiceGroup cgChoices;
    	private ChoiceGroup cgDefaultChoices;
    	private String strSelectedIndex, strSelectedChoice, strSelectedChoiceForStateChange;
    	
    	public ChoiceGroupOptionActionTest4() {
    		// Get the display object for the MIDlet.
    		display = Display.getDisplay(this);
    
    		// Create the Exit and Go commands.
    		exitCommand = new Command("Exit", Command.EXIT, 2);
    		goCommand = new Command("Go", Command.OK, 2);
    		saveCommand = new Command("Save", Command.OK, 2);
    		cancelCommand = new Command("Cancel", Command.CANCEL, 2);
    		addCommand = new Command("Add", Command.OK, 2);
    
    		// Create the screen form.
    		screen = new Form("Main Screen");
    
    		// Set the Exit and Go commands for the screen.
    		screen.addCommand(exitCommand);
    		screen.addCommand(goCommand);
    		screen.setCommandListener(this);
    		screen.setItemStateListener(this);
    	}
    
    	//public void startApp() throws MIDletStateChangeException {
    	public void startApp() {
    	
    		// Open the record store.
    		try {
    		choicesTestDb = RecordStore.openRecordStore("choicestestfile4", true);
    		} catch (RecordStoreNotFoundException rsnfe) {
    		// Handle the exception.
    		} catch (RecordStoreFullException fsfe) {
    		// Handle the exception.
    		} catch (RecordStoreException rse) {
    		// Handle the exception.
    		}
    
    		// If the record store has no records yet, write to it.
    		try {
    			intNumberOfRecords = choicesTestDb.getNumRecords();
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    		if (intNumberOfRecords == 0) {
    			writeRecordToChoicesRecordStore("Choice 1");
    			writeRecordToChoicesRecordStore("Choice 2");
    			writeRecordToChoicesRecordStore("Choice 3");
    		}
    	
    			String[] strDefaultChoices = { "(Add a choice)" };
    			cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    			
    			/*
    			// Empty the choice group before enumerating the record store.
    			for (int j = cgDefaultChoices.size(); j > 0; j--) {
    				cgDefaultChoices.delete(j - 1);
    			}
    			*/
    
    
    		// Read from the choices test record store and display to the screen.
    		String strTheChoice = null;
    		try{
    			if (choicesTestDb.getNumRecords() > 0) {
    				//Comparator comp = new Comparator();
    				//RecordEnumeration reChoicesTestEnumeration = choicesTestDb.enumerateRecords(null, comp, false);
    				RecordEnumeration reChoicesTestEnumeration = choicesTestDb.enumerateRecords(null, null, false);
    
    				while (reChoicesTestEnumeration.hasNextElement()) {
    				//String strTheChoice = new String(reChoicesTestEnumeration.nextRecord());
    				try {
    					strTheChoice = new String(reChoicesTestEnumeration.nextRecord());
    				} catch (RecordStoreException ex) {
    					ex.printStackTrace();
    				}
    				cgDefaultChoices.append(strTheChoice, null);
    				//System.out.println("------------------------------"); // This can be uncommented for testing purposes.
    				//System.out.println(strTheChoice);                   // This can be uncommented for testing purposes.
    				//System.out.println("------------------------------"); // This can be uncommented for testing purposes.
    				}
    			}
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    
    		screen.append(cgDefaultChoices);
    		
    		// Make the first item in the choice group be selected.
    		cgDefaultChoices.setSelectedIndex(0, true);
    	
    		int intSelectedChoice = cgDefaultChoices.getSelectedIndex();
    		//int indexSelected = cgDefaultChoices.getSelectedIndex();///////////////////////////////////////
    		strSelectedIndex = Integer.toString(intSelectedChoice);
    		strSelectedChoice = cgDefaultChoices.getString(intSelectedChoice);
    		
    		// Set the current display to the screen.
    		display.setCurrent(screen);
    	
    		// Close the record store.
    		try {
    			choicesTestDb.closeRecordStore();
    		}
    		catch (Exception error) {
    			alert = new Alert("Error Closing", 
    				error.toString(), null, AlertType.WARNING); 
    			alert.setTimeout(Alert.FOREVER); 
    			display.setCurrent(alert);
    		}
    
    	}
    
    	public void pauseApp() {
    	}
    
    	public void destroyApp(boolean unconditional) {
    	}
    
    
    	public void goCom() {
    	
    		// Create the add choice form.
    		frmAddChoice = new Form("Add Choice");
    
    		// Set the Exit and Save commands for the add choice form.
    		frmAddChoice.addCommand(cancelCommand);
    		// If the selected choice is "(Add a choice)", then display the Add command; otherwise, don't display another command.
    		if (strSelectedChoice == "(Add a choice)") {
    			frmAddChoice.addCommand(addCommand);
    		} else {
    			// Don't display another command.
    		}
    		frmAddChoice.setCommandListener(this);
    
    		// Add a text field for entering the new choice.
    		frmAddChoice.append(new StringItem("", "Testing\n"));//////////////////////////////////////////////////////////////////
    		frmAddChoice.append(new StringItem("", strSelectedIndex + "\n"));//////////////////////////////////////////////////////////////////
    		//frmAddChoice.append(new StringItem("", cgDefaultChoices.size()-intSelectedIndex + "\n"));
    		frmAddChoice.append(new StringItem("", strSelectedChoice));//////////////////////////////////////////////////////////////////
    		// Only display the below text field if the choice "(Add a choice)" was selected.
    		if (strSelectedChoice == "(Add a choice)") {
    			TextField addChoiceField = new TextField("New choice to add", "", 40, TextField.ANY);
    			frmAddChoice.append(addChoiceField);
    		}
    	
    		// Set the current display to the add choice form.
    		display.setCurrent(frmAddChoice);
    	}
    
    	public void cancelCom() {
    		display.setCurrent(screen);
    	}
    
    	public void commandAction(Command c, Displayable s) {
    		if (c == exitCommand) {
    			destroyApp(false);
    			notifyDestroyed();
    		} else if (c == goCommand) {
    			goCom();
    		} else if (c == cancelCommand) {
    			cancelCom();
    		}
    	}
    
    	/*
    	public void itemStateChanged(Item item) {
    		intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    		strSelectedChoiceForStateChange = cgDefaultChoices.getString(intSelectedIndex);
    		System.out.println("Inside itemStateChanged() to choice group index number " + intSelectedIndex + " (" + strSelectedChoiceForStateChange + ")");
    	}
    	*/
    	public void itemStateChanged(Item item) {
    	
    		if (item == cgDefaultChoices) {
    			intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    			//if (intSelectedIndex == null) {
    			//	intSelectedIndex = 3;
    			//}
    			strSelectedChoiceForStateChange = cgDefaultChoices.getString(intSelectedIndex);
    			System.out.println("Inside itemStateChanged() to choice group index number " + intSelectedIndex + " (" + strSelectedChoiceForStateChange + ")");			
    			// Display the add form screen along with some testing info.
    			strSelectedIndex = Integer.toString(intSelectedIndex);
    			strSelectedChoice = cgDefaultChoices.getString(intSelectedIndex);
    		}
    	}
    
    	public void writeRecordToChoicesRecordStore(String strRecord) {
    		byte[] bytesRecord = strRecord.getBytes();
    		try {
    			choicesTestDb.addRecord(bytesRecord, 0, bytesRecord.length);
    		} catch (RecordStoreException e) {
    				e.printStackTrace();
    		}
    	}
    
    }

  10. #10
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    (This message post shows the bottom half of the code from the 5th version of the MIDlet):

    Code:
    	//public void startApp() throws MIDletStateChangeException {
    	public void startApp() {
    	
    		// Create a text field for the main screen.
    		//TextField sampleTextField = new TextField("This is a sample text field", "", 40, TextField.ANY);
    		sampleTextField = new TextField("This is a sample text field", "", 40, TextField.ANY);
    		screen.append(sampleTextField);
    		
    		// Open the record store.
    		try {
    		choicesTestDb = RecordStore.openRecordStore("choicestestfile5", true);
    		} catch (RecordStoreNotFoundException rsnfe) {
    		// Handle the exception.
    		} catch (RecordStoreFullException fsfe) {
    		// Handle the exception.
    		} catch (RecordStoreException rse) {
    		// Handle the exception.
    		}
    
    		// If the record store has no records yet, write to it.
    		try {
    			intNumberOfRecords = choicesTestDb.getNumRecords();
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    		if (intNumberOfRecords == 0) {
    			writeRecordToChoicesRecordStore("Choice 1");
    			writeRecordToChoicesRecordStore("Choice 2");
    			writeRecordToChoicesRecordStore("Choice 3");
    		}
    	
    			String[] strDefaultChoices = { "(Add a choice)" };
    			cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    			
    			/*
    			// Empty the choice group before enumerating the record store.
    			for (int j = cgDefaultChoices.size(); j > 0; j--) {
    				cgDefaultChoices.delete(j - 1);
    			}
    			*/
    
    
    		// Read from the choices test record store and display to the screen.
    		String strTheChoice = null;
    		try{
    			if (choicesTestDb.getNumRecords() > 0) {
    				//Comparator comp = new Comparator();
    				//RecordEnumeration reChoicesTestEnumeration = choicesTestDb.enumerateRecords(null, comp, false);
    				RecordEnumeration reChoicesTestEnumeration = choicesTestDb.enumerateRecords(null, null, false);
    
    				while (reChoicesTestEnumeration.hasNextElement()) {
    				//String strTheChoice = new String(reChoicesTestEnumeration.nextRecord());
    				try {
    					strTheChoice = new String(reChoicesTestEnumeration.nextRecord());
    				} catch (RecordStoreException ex) {
    					ex.printStackTrace();
    				}
    				cgDefaultChoices.append(strTheChoice, null);
    				//System.out.println("------------------------------"); // This can be uncommented for testing purposes.
    				//System.out.println(strTheChoice);                   // This can be uncommented for testing purposes.
    				//System.out.println("------------------------------"); // This can be uncommented for testing purposes.
    				}
    			}
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    
    		screen.append(cgDefaultChoices);
    		
    		// Make the first item in the choice group be selected.
    		cgDefaultChoices.setSelectedIndex(0, true);
    	
    		int intSelectedChoice = cgDefaultChoices.getSelectedIndex();
    		//int indexSelected = cgDefaultChoices.getSelectedIndex();///////////////////////////////////////
    		strSelectedIndex = Integer.toString(intSelectedChoice);
    		strSelectedChoice = cgDefaultChoices.getString(intSelectedChoice);
    		
    		// Set the current display to the screen.
    		display.setCurrent(screen);
    	
    		// Close the record store.
    		try {
    			choicesTestDb.closeRecordStore();
    		}
    		catch (Exception error) {
    			alert = new Alert("Error Closing", 
    				error.toString(), null, AlertType.WARNING); 
    			alert.setTimeout(Alert.FOREVER); 
    			display.setCurrent(alert);
    		}
    
    	}
    
    	public void pauseApp() {
    	}
    
    	public void destroyApp(boolean unconditional) {
    	}
    
    
    	//public void goCom() { // Use the below for "Add" instead of "Go"?
    	public void addCom() {
    	
    		// Create the add choice form.
    		frmAddChoice = new Form("Add Choice");
    
    		// Set the "Cancel" and "Save" commands for the add choice form.
    		frmAddChoice.addCommand(cancelCommand);
    		// If the selected choice is "(Add a choice)", then display the Add command; otherwise, don't display another command.
    		if (strSelectedChoice == "(Add a choice)") {
    			//frmAddChoice.addCommand(addCommand); // Use the saveNewChoiceCommand instead.
    			frmAddChoice.addCommand(saveNewChoiceCommand);
    		} else {
    			// Don't display another command.
    		}
    		frmAddChoice.setCommandListener(this);
    
    		// Add a text field for entering the new choice.
    		frmAddChoice.append(new StringItem("", "Testing\n"));//////////////////////////////////////////////////////////////////
    		frmAddChoice.append(new StringItem("", strSelectedIndex + "\n"));//////////////////////////////////////////////////////////////////
    		//frmAddChoice.append(new StringItem("", cgDefaultChoices.size()-intSelectedIndex + "\n"));
    		frmAddChoice.append(new StringItem("", strSelectedChoice));//////////////////////////////////////////////////////////////////
    		// Only display the below text field if the choice "(Add a choice)" was selected.
    		if (strSelectedChoice == "(Add a choice)") {
    			TextField addChoiceField = new TextField("New choice to add", "", 40, TextField.ANY);
    			frmAddChoice.append(addChoiceField);
    		}
    	
    		// Set the current display to the add choice form.
    		display.setCurrent(frmAddChoice);
    	}
    
    	public void saveCom() {
    		
    		// Create the save form for testing purposes, in order to display what would be saved.
    		frmDisplaySavedInfo = new Form("Saved Info");
    		
    		// Set the "Cancel" command for the save form.
    		frmDisplaySavedInfo.addCommand(cancelCommand);
    		frmDisplaySavedInfo.setCommandListener(this);
    		
    		frmDisplaySavedInfo.append(new StringItem("", "Testing\n"));//////////////////////////////////////////////////////////////////
    		frmDisplaySavedInfo.append(new StringItem("", strSelectedIndex + "\n"));//////////////////////////////////////////////////////////////////
    		//frmDisplaySavedInfo.append(new StringItem("", cgDefaultChoices.size()-intSelectedIndex + "\n"));
    		frmDisplaySavedInfo.append(new StringItem("", strSelectedChoice));//////////////////////////////////////////////////////////////////
    		
    		// Set the current display to the save form.
    		display.setCurrent(frmDisplaySavedInfo);
    	}
    	
    	public void saveNewChoiceCom() {
    		// Don't actually save anything yet.  Instead, return to the main screen.
    		display.setCurrent(screen);
    	}
    
    	public void cancelCom() {
    		display.setCurrent(screen);
    	}
    
    	public void commandAction(Command c, Displayable s) {
    		if (c == exitCommand) {
    			destroyApp(false);
    			notifyDestroyed();
    		//} else if (c == goCommand) {  // Use the below for "Add" instead of "Go"?
    		//	goCom();					// Use the below for "Add" instead of "Go"?
    		} else if (c == addCommand) {
    			addCom();
    		} else if (c == saveCommand) {
    			saveCom();
    		} else if (c == saveNewChoiceCommand) {
    			saveNewChoiceCom();
    		} else if (c == cancelCommand) {
    			cancelCom();
    		}
    	}
    
    	/*
    	public void itemStateChanged(Item item) {
    		intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    		strSelectedChoiceForStateChange = cgDefaultChoices.getString(intSelectedIndex);
    		System.out.println("Inside itemStateChanged() to choice group index number " + intSelectedIndex + " (" + strSelectedChoiceForStateChange + ")");
    	}
    	*/
    	public void itemStateChanged(Item item) {
    
    		if (item == sampleTextField) {
    			// Remove the "Add" command.
    			screen.removeCommand(addCommand);
    		}
    		
    		if (item == cgDefaultChoices) {
    			intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    			//if (intSelectedIndex == null) {
    			//	intSelectedIndex = 3;
    			//}
    			strSelectedChoiceForStateChange = cgDefaultChoices.getString(intSelectedIndex);
    			System.out.println("Inside itemStateChanged() to choice group index number " + intSelectedIndex + " (" + strSelectedChoiceForStateChange + ")");			
    			if (intSelectedIndex == 0) {
    				// Remove the "Save" command and add the "Add" command.
    				screen.removeCommand(saveCommand);
    				screen.addCommand(addCommand);
    			} else {
    				// Remove the "Add" command and add the "Save" command.
    				screen.removeCommand(addCommand);
    				screen.addCommand(saveCommand);
    			}
    			
    			// Display the add form screen along with some testing info.
    			strSelectedIndex = Integer.toString(intSelectedIndex);
    			strSelectedChoice = cgDefaultChoices.getString(intSelectedIndex);
    		}
    	}
    
    	public void writeRecordToChoicesRecordStore(String strRecord) {
    		byte[] bytesRecord = strRecord.getBytes();
    		try {
    			choicesTestDb.addRecord(bytesRecord, 0, bytesRecord.length);
    		} catch (RecordStoreException e) {
    				e.printStackTrace();
    		}
    	}
    
    }
    Last edited by John_123; 2011-10-20 at 01:42.

  11. #11
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    (This message post, the third of three posts that together would have too many characters for one post, contains some explanations, along with the top half of the code from the 5th version of the MIDlet.)

    In the 5th version of the MIDlet, a text field has been added to the top of the main screen. Also, instead of the "Go" button, I would like to have three possibilities displayed: either no button at all, an "Add" button, or a "Save" button. I would like there to be no button when the focus starts on the text field at the top of the main display. Then, when the focus moves to the choice group where "(Add a choice)" is selected by default, I would like the "Add" button to display. Finally, when a different choice in that choice group is selected, I would like the "Add" button to be replaced by the "Save" button.

    Right now, I am unable to make no button appear at the beginning. Instead, the "Add" button appears, and once I type some characters into the text field, the "Add" button then disappears. In addition, once the "Add" button disappears after some typing, when focus is then directed to the choice group, there is no button displayed, even though "(Add a choice)" is selected by default. I tried to accomplish the changing of the buttons by means of the itemStateChanged method.

    Below is the code for the top half of the 5th version of the MIDlet:

    Code:
    //
    //  ChoiceGroupOptionActionTest5.java
    //  
    //
    //
    /* This code reflects content in the discussion thread at the below web page:
    http://www.developer.nokia.com/Community/Discussion/showthread.php?229634-Need-help-with-an-ItemStateListener.&p=864423#post864423
    */
    // This version 5 differs from version 4 in that the ItemStateListener is used to change a button on the main screen.
    // Instead of a "go" button, there is now an "Add" button, which changes to "Save".
    
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.util.*;
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.rms.*;
    import java.lang.*;
    
    public class ChoiceGroupOptionActionTest5 extends MIDlet implements CommandListener, ItemStateListener {
    
    	private RecordStore choicesTestDb = null;
    	private Command exitCommand, goCommand, saveCommand, saveNewChoiceCommand, cancelCommand, addCommand;
    	private Display display;
    	private Form screen;
    	private Form frmAddChoice;
    	private Form frmDisplaySavedInfo;
    	private Alert alert;
    	private int i, intNumberOfRecords, intSelectedIndex;
    	private StringBuffer strbBuffer;
    	private ChoiceGroup cgChoices;
    	private ChoiceGroup cgDefaultChoices;
    	private TextField sampleTextField;
    	private String strSelectedIndex, strSelectedChoice, strSelectedChoiceForStateChange;
    	
    	public ChoiceGroupOptionActionTest5() {
    		// Get the display object for the MIDlet.
    		display = Display.getDisplay(this);
    
    		// Create the Exit and Go commands.
    		exitCommand = new Command("Exit", Command.EXIT, 2);
    		goCommand = new Command("Go", Command.OK, 2);
    		saveCommand = new Command("Save", Command.OK, 2);
    		saveNewChoiceCommand = new Command("Save", Command.OK, 2);
    		cancelCommand = new Command("Cancel", Command.CANCEL, 2);
    		addCommand = new Command("Add", Command.OK, 2);
    
    		// Create the screen form.
    		screen = new Form("Main Screen");
    
    		// Set the Exit and Add commands for the screen.
    		screen.addCommand(exitCommand);
    		//screen.addCommand(goCommand); // Use the below for "Add" instead of "Go"?
    		screen.addCommand(addCommand);
    		screen.setCommandListener(this);
    		screen.setItemStateListener(this);
    	}
    (The bottom half of the code is in the post that was made previous to this one.)

    Any insights would be greatly appreciated.

  12. #12
    Nokia Developer Expert
    Join Date
    Aug 2011
    Posts
    555

    Re: Need help with an ItemStateListener.

    One way to do this is to add a blank Command (of Item type) to your TextField (not to the screen form) and attach an ItemCommandListener (again to your TextField and not to the form). Then you do the same with a different command to your ChoiceGroup. In this way every time the focus is on either the TextField or the ChoiceGroup the relevant command automatically displays. And finally you can use the itemStateChange method to distinguish between the first and the rest of the ChoiceGroup's options.

    Also please make sure that you go through the detailed information regarding UI and Graphics here:
    http://library.developer.nokia.com/i...75D356220.html

    I have removed the additional functionality from your code, and I have kept only the UI. Here is how a solution to your problem could look like:
    Code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.rms.*;
    
    public class ChoiceGroupOptionActionTest extends MIDlet implements CommandListener, ItemStateListener, ItemCommandListener {
    
    	private RecordStore choicesTestDb = null;
    	private Command exitCommand, saveCommand, myAddCommand, emptyCommand;
    	private Display display;
    	private Form screen;
    	private Alert alert;
    	private int intNumberOfRecords, intSelectedIndex;
    	private ChoiceGroup cgDefaultChoices;
    	private TextField sampleTextField;
    	
    	public ChoiceGroupOptionActionTest() {
    		display = Display.getDisplay(this);
    		exitCommand = new Command("Exit", Command.EXIT, 2);
    		saveCommand = new Command("Save", Command.OK, 2);
    		myAddCommand = new Command("Add", Command.ITEM, 2);
    		emptyCommand = new Command("", Command.ITEM, 2);
    		screen = new Form("Main Screen");
    		screen.addCommand(exitCommand);
    		screen.setCommandListener(this);
    		screen.setItemStateListener(this);
    	}
    	public void startApp() {
    		sampleTextField = new TextField("This is a sample text field", "", 40, TextField.ANY);
    		sampleTextField.addCommand(emptyCommand);
    		sampleTextField.setItemCommandListener(this);
    		screen.append(sampleTextField);
    
    		try {
    		choicesTestDb = RecordStore.openRecordStore("choicestestfile5", true);
    		} catch (RecordStoreNotFoundException rsnfe) {
    		} catch (RecordStoreFullException fsfe) {
    		} catch (RecordStoreException rse) {
    		}
    		try {
    			intNumberOfRecords = choicesTestDb.getNumRecords();
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    		if (intNumberOfRecords == 0) {
    			writeRecordToChoicesRecordStore("Choice 1");
    			writeRecordToChoicesRecordStore("Choice 2");
    			writeRecordToChoicesRecordStore("Choice 3");
    		}
    	
    			String[] strDefaultChoices = { "(Add a choice)" };
    			cgDefaultChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    			cgDefaultChoices.addCommand(myAddCommand);
    			cgDefaultChoices.setItemCommandListener(this);
    		String strTheChoice = null;
    		try{
    			if (choicesTestDb.getNumRecords() > 0) {
    				RecordEnumeration reChoicesTestEnumeration = choicesTestDb.enumerateRecords(null, null, false);
    
    				while (reChoicesTestEnumeration.hasNextElement()) {
    				try {
    					strTheChoice = new String(reChoicesTestEnumeration.nextRecord());
    				} catch (RecordStoreException ex) {
    					ex.printStackTrace();
    				}
    				cgDefaultChoices.append(strTheChoice, null);
    				}
    			}
    		} catch (RecordStoreNotOpenException ex) {
    			ex.printStackTrace();
    		}
    		screen.append(cgDefaultChoices);
    		cgDefaultChoices.setSelectedIndex(0, true);	
    		display.setCurrent(screen);
    		try {
    			choicesTestDb.closeRecordStore();
    		}
    		catch (Exception error) {
    			alert = new Alert("Error Closing", 
    				error.toString(), null, AlertType.WARNING); 
    			alert.setTimeout(Alert.FOREVER); 
    			display.setCurrent(alert);
    		}
    	}
    	public void pauseApp() {
    	}
    	public void destroyApp(boolean unconditional) {
    	}
    	public void itemStateChanged(Item item) {	
    		if (item == cgDefaultChoices) {
    			intSelectedIndex = cgDefaultChoices.getSelectedIndex();
    			if (intSelectedIndex == 0) {
    				cgDefaultChoices.removeCommand(saveCommand);
    				cgDefaultChoices.addCommand(myAddCommand);
    			} else {
    				cgDefaultChoices.removeCommand(myAddCommand);
    				cgDefaultChoices.addCommand(saveCommand);
    			}
    		}
    	}
    	public void writeRecordToChoicesRecordStore(String strRecord) {
    		byte[] bytesRecord = strRecord.getBytes();
    		try {
    			choicesTestDb.addRecord(bytesRecord, 0, bytesRecord.length);
    		} catch (RecordStoreException e) {
    				e.printStackTrace();
    		}
    	}
    	public void commandAction(Command c, Item item) {}
    	public void commandAction(Command c, Displayable d) {
    		// TODO Auto-generated method stub
    		
    	}
    }
    Please note that this doesn't work on Touch UIs. You might want to consult the link I have provided for further UI implementation options.
    Last edited by skalogir; 2011-10-20 at 12:40.

  13. #13
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    Thank you once again, skalogir. I plan to run and study the code and check out the link.

  14. #14
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    This is the bottom half from the code of version 7:

    Code:
    	// Close the default choices record store.
    	try {
    		defaultChoicesTestDb.closeRecordStore();
    	}
    	catch (Exception error) {
    		alert = new Alert("Error Closing", 
    			error.toString(), null, AlertType.WARNING); 
    		alert.setTimeout(Alert.FOREVER); 
    		display.setCurrent(alert);
    	}
    
    	// Close the user choices record store.
    	try {
    		userChoicesTestDb.closeRecordStore();
    	}
    	catch (Exception error) {
    		alert = new Alert("Error Closing", 
    						  error.toString(), null, AlertType.WARNING); 
    		alert.setTimeout(Alert.FOREVER); 
    		display.setCurrent(alert);
    	}			
    	
    	// Close the sorted user choices record store.
    	try {
    		sortedUserChoicesTestDb.closeRecordStore();
    	}
    	catch (Exception error) {
    		alert = new Alert("Error Closing", 
    						  error.toString(), null, AlertType.WARNING); 
    		alert.setTimeout(Alert.FOREVER); 
    		display.setCurrent(alert);
    	}
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
    }
    
    public void addCom() {
    
    	intSelectedChoice = cgChoices.getSelectedIndex();
    	strSelectedIndex = Integer.toString(intSelectedChoice);
    	strSelectedChoice = cgChoices.getString(intSelectedChoice);
    
    	// Create the add choice form.
    	frmAddChoice = new Form("Add");
    
    	// Set the "Cancel" and "Save" commands for the add choice form.
    	frmAddChoice.addCommand(cancelCommand);
    	// If the selected choice is "(Add a choice)", then display the Add command; otherwise, don't display another command.
    	if (strSelectedChoice == "(Add a choice)") {
    		frmAddChoice.addCommand(saveNewChoiceCommand);
    	} else {
    		// Don't display another command.
    	}
    	frmAddChoice.setCommandListener(this);
    
    	// Add a text field for entering the new choice.
    	frmAddChoice.append(new StringItem("", "Testing\n"));
    	frmAddChoice.append(new StringItem("", strSelectedIndex + "\n"));
    	frmAddChoice.append(new StringItem("", strSelectedChoice));
    	// Only display the below text field if the choice "(Add a choice)" was selected.
    		TextField addChoiceField = new TextField("New choice to add", "", 40, TextField.ANY);
    		frmAddChoice.append(addChoiceField);
    
    	// Set the current display to the add choice form.
    	display.setCurrent(frmAddChoice);
    }
    
    public void saveCom() {
    
    	intSelectedChoice = cgChoices.getSelectedIndex();
    	strSelectedIndex = Integer.toString(intSelectedChoice);
    	strSelectedChoice = cgChoices.getString(intSelectedChoice);
    
    	// Create the save form for testing purposes, in order to display what would be saved.
    	frmDisplaySavedInfo = new Form("Saved Info");
    	
    	// Set the "Cancel" command for the save form.
    	frmDisplaySavedInfo.addCommand(cancelCommand);
    	frmDisplaySavedInfo.setCommandListener(this);
    	
    	frmDisplaySavedInfo.append(new StringItem("", "Testing\n"));
    	frmDisplaySavedInfo.append(new StringItem("", strSelectedIndex + "\n"));
    	frmDisplaySavedInfo.append(new StringItem("", strSelectedChoice));
    	
    	// Set the current display to the save form.
    	display.setCurrent(frmDisplaySavedInfo);
    }
    
    public void saveNewChoiceCom() {
    	// Don't actually save anything yet.  Instead, return to the main screen.
    	display.setCurrent(screen);
    }
    
    public void cancelCom() {
    	display.setCurrent(screen);
    }
    
    	public void itemStateChanged(Item item) {	
    		if (item == sampleTextField) {
    			intSelectedIndex = cgChoices.getSelectedIndex();
    			if (intSelectedIndex == 0) {
    				sampleTextField.removeCommand(saveCommand);
    				sampleTextField.addCommand(addAChoiceCommand);
    				System.out.println("The intSelectedIndex:\t" + intSelectedIndex);
    			} else {
    				sampleTextField.removeCommand(addAChoiceCommand);
    				sampleTextField.addCommand(saveCommand);
    				System.out.println("The intSelectedIndex:\t" + intSelectedIndex);
    			}
    		}
    		if (item == cgChoices) {
    			intSelectedIndex = cgChoices.getSelectedIndex();
    			if (intSelectedIndex == 0) {
    				cgChoices.removeCommand(saveCommand);
    				cgChoices.addCommand(addAChoiceCommand);
    				System.out.println("The intSelectedIndex:\t" + intSelectedIndex);
    			} else {
    				cgChoices.removeCommand(addAChoiceCommand);
    				cgChoices.addCommand(saveCommand);
    				System.out.println("The intSelectedIndex:\t" + intSelectedIndex);
    			}
    		}
    	}
    	
    	public void writeRecordToDefaultStore(String strRecord) {
    		byte[] bytesRecord = strRecord.getBytes();
    		try {
    			defaultChoicesTestDb.addRecord(bytesRecord, 0, bytesRecord.length);
    		} catch (RecordStoreException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public void writeRecordToUserStore(String strUserChoice) {
    		byte[] bytesUserChoice = strUserChoice.getBytes();
    		try {
    			userChoicesTestDb.addRecord(bytesUserChoice, 0, bytesUserChoice.length);
    		} catch (RecordStoreException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	
    	public void writeRecordToSortedUserStore(String strSortedUserChoice) {
    		byte[] bytesSortedUserChoice = strSortedUserChoice.getBytes();
    		try {
    			sortedUserChoicesTestDb.addRecord(bytesSortedUserChoice, 0, bytesSortedUserChoice.length);
    		} catch (RecordStoreException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public void commandAction(Command c, Item item) {
    		if (c == exitCommand) {
    			destroyApp(false);
    			notifyDestroyed();
    		} else if (c == addAChoiceCommand) {
    			if (intSelectedIndex > 0) {
    				alert = new Alert("Cannot add because...", "\"(Add a choice)\" is not selected. The \"Save\" command will become " + 
    					"available after a character is typed or deleted, or if the cursor is moved outside " + 
    					"the text field.", null, AlertType.WARNING);
    				alert.setTimeout(Alert.FOREVER);
    				display.setCurrent(alert);
    			} else {
    				addCom();
    			}
    			System.out.println("The addAChoiceCommand button was pressed.\t" + intSelectedIndex);
    		} else if (c == saveCommand) {
    			if (intSelectedIndex == 0) {
    				alert = new Alert("Cannot save because...", "\"(Add a choice)\" is selected. The \"Add\" command will become available " + 
    					"after a character is typed or deleted, or if the cursor is moved outside  " + 
    					"the text field.", null, AlertType.WARNING);
    				alert.setTimeout(Alert.FOREVER);
    				display.setCurrent(alert);
    			} else {
    				saveCom();
    			}
    		} else if (c == saveNewChoiceCommand) {
    			saveNewChoiceCom();
    		} else if (c == cancelCommand) {
    			cancelCom();
    		}
    	}
    	
    	//public void commandAction(Command c, Displayable s) {
    	public void commandAction(Command c, Displayable d) {
    		if (c == exitCommand) {
    			destroyApp(false);
    			notifyDestroyed();
    		} else if (c == addAChoiceCommand) {
    			addCom();
    			System.out.println("The addAChoiceCommand button was pressed.");
    		} else if (c == saveCommand) {
    			saveCom();
    		} else if (c == saveNewChoiceCommand) {
    			saveNewChoiceCom();
    		} else if (c == cancelCommand) {
    			cancelCom();
    		}
    	}
    }
    
    class Comparator implements RecordComparator {
    	
    	public int compare(byte[] record1, byte[] record2) {
    		
    		// Convert the two records to string objects.
    		String string1 = new String(record1);
    		String string2 = new String(record2);
    		
    		// Compare the two strings in order to determine the alphabetical order of them.
    		int comparison = string1.compareTo(string2);
    		if (comparison == 0) {
    			return RecordComparator.EQUIVALENT;
    		} else if (comparison < 0) {			// This is for a regular sort order.
    			//} else if (comparison > 0) {			// This is for a reverse sort order.
    			return RecordComparator.PRECEDES;
    		} else {
    			return RecordComparator.FOLLOWS;
    		}
    	}
    }
    
    class TheFilter implements RecordFilter {
    	public boolean matches(byte[] candidate) {
    		String c = new String(candidate);
    		if (c.startsWith("Food")) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    }
    
    //public class RF implements RecordFilter {
    class RF implements RecordFilter {
    	
    	private String match;
    	
    	public RF(String match)
    	{
    		this.match=match.toLowerCase();
    	}
    	
    	public boolean matches(byte[] candidate) {
    		String s=new String(candidate);
    		if (s.toLowerCase().equals(match))
    			return true;
    		else
    			return false;
    	}
    }

  15. #15
    Regular Contributor
    Join Date
    Sep 2011
    Posts
    73

    Re: Need help with an ItemStateListener.

    I ran the code; it was very helpful. Here is some code from version 7. It seems to work OK. I removed some of the commented-out parts. This is from the top half:

    Code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.util.*;
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.rms.*;
    
    import java.lang.*;
    
    public class ChoiceGroupOptionActionTest7 extends MIDlet implements CommandListener, ItemStateListener, ItemCommandListener {
    
    private RecordStore defaultChoicesTestDb = null;
    private RecordStore userChoicesTestDb = null;
    private RecordStore sortedUserChoicesTestDb = null;
    private Command exitCommand, goCommand, saveCommand, saveNewChoiceCommand, cancelCommand, addAChoiceCommand;
    private Display display;
    private Form screen;
    private Form frmAddChoice;
    private Form frmDisplaySavedInfo;
    private Alert alert;
    private int i, intNumberOfRecords, intSelectedIndex, intSelectedChoice;
    private int intNumberOfDefaultRecords, intNumberOfUserRecords, intNumberOfSortedUserRecords;
    private ChoiceGroup cgChoices;
    private TextField sampleTextField;
    private String strSelectedIndex, strSelectedChoice, strSelectedChoiceForStateChange;
    private Comparator comparator = null;
    
    public ChoiceGroupOptionActionTest7() {
    	// Get the display object for the MIDlet.
    	display = Display.getDisplay(this);
    
    	// Create the Exit and Go commands.
    	exitCommand = new Command("Exit", Command.EXIT, 2);
    	goCommand = new Command("Go", Command.OK, 2);
    	saveCommand = new Command("Save", Command.OK, 2);
    	saveNewChoiceCommand = new Command("Save", Command.OK, 2);
    	cancelCommand = new Command("Cancel", Command.CANCEL, 2);
    	addAChoiceCommand = new Command("Add", Command.OK, 2);
    
    	// Create the screen form.
    	screen = new Form("Main Screen");
    
    	// Set the Exit and Add commands for the screen.
    	screen.addCommand(exitCommand);
    	screen.setCommandListener(this);
    	screen.setItemStateListener(this);
    }
    
    //public void startApp() throws MIDletStateChangeException {
    public void startApp() {
    
    	// Create a text field for the main screen.
    	sampleTextField = new TextField("This is a sample text field", "", 40, TextField.ANY);
    	sampleTextField.addCommand(addAChoiceCommand); // In the beginning, this displays an "Add" button when the display is selected.
    	sampleTextField.setItemCommandListener(this);
    	screen.append(sampleTextField);
    	
    	// Open the default choices record store.
    	try {
    	defaultChoicesTestDb = RecordStore.openRecordStore("defaultchoicestestfile7", true);
    	} catch (RecordStoreNotFoundException rsnfe) {
    	// Handle the exception.
    	} catch (RecordStoreFullException fsfe) {
    	// Handle the exception.
    	} catch (RecordStoreException rse) {
    	// Handle the exception.
    	}
    
    	// Open the user choices record store.
    	try {
    		userChoicesTestDb = RecordStore.openRecordStore("userchoicestestfile7", true);
    	} catch (RecordStoreNotFoundException rsnfe) {
    		// Handle the exception.
    	} catch (RecordStoreFullException fsfe) {
    		// Handle the exception.
    	} catch (RecordStoreException rse) {
    		// Handle the exception.
    	}
    
    	// Open the sorted user choices record store.
    	try {
    		sortedUserChoicesTestDb = RecordStore.openRecordStore("sorteduserchoicestestfile7", true);
    	} catch (RecordStoreNotFoundException rsnfe) {
    		// Handle the exception.
    	} catch (RecordStoreFullException fsfe) {
    		// Handle the exception.
    	} catch (RecordStoreException rse) {
    		// Handle the exception.
    	}
    	
    	// If the default choices record store has no records yet, write to it.
    	try {
    		intNumberOfRecords = defaultChoicesTestDb.getNumRecords();
    	} catch (RecordStoreNotOpenException ex) {
    		ex.printStackTrace();
    	}
    	if (intNumberOfRecords == 0) {
    		writeRecordToDefaultStore("Choice 1");
    		writeRecordToDefaultStore("Choice 2");
    		writeRecordToDefaultStore("Choice 3");
    	}
    	
    	String[] strDefaultChoices = { "(Add a choice)" };
    	cgChoices = new ChoiceGroup("Choices:", List.EXCLUSIVE, strDefaultChoices, null);
    	cgChoices.addCommand(addAChoiceCommand);
    	cgChoices.setItemCommandListener(this);
    			
    	// Read from the default choices record store and write to the user choices record store.
    	String strTheChoice = null;
    	try{
    		if (defaultChoicesTestDb.getNumRecords() > 0) {
    			RecordEnumeration reDefaultChoicesEnumeration = defaultChoicesTestDb.enumerateRecords(null, null, false);
    			try {
    				intNumberOfUserRecords = userChoicesTestDb.getNumRecords();
    			} catch (RecordStoreNotOpenException ex) {
    				ex.printStackTrace();
    			}
    			// If the user choices record store does not yet have the default choices, write them to it.
    			if (intNumberOfUserRecords == 0) {
    				while (reDefaultChoicesEnumeration.hasNextElement()) {
    					try {
    						strTheChoice = new String(reDefaultChoicesEnumeration.nextRecord());
    					} catch (RecordStoreException ex) {
    						ex.printStackTrace();
    					}
    					writeRecordToUserStore(strTheChoice);
    				}
    			}
    		}
    	} catch (RecordStoreNotOpenException ex) {
    		ex.printStackTrace();
    	}
    
    	// Read from the user choices record store.
    	String strTheUserChoice = null;
    	try{
    		if (userChoicesTestDb.getNumRecords() > 0) {
    			RecordEnumeration reUserChoicesEnumeration = userChoicesTestDb.enumerateRecords(null, null, false);
    			while (reUserChoicesEnumeration.hasNextElement()) {
    				try {
    					strTheUserChoice = new String(reUserChoicesEnumeration.nextRecord());
    				} catch (RecordStoreException ex) {
    					ex.printStackTrace();
    				}
    				System.out.println("------------------------------");
    				System.out.println("The user choice: " + strTheUserChoice);
    				System.out.println("------------------------------");
    			}
    		}
    	} catch (RecordStoreNotOpenException ex) {
    		ex.printStackTrace();
    	}
    	
    	// Close the sorted user record store, delete it, and open it again
    	// before writing the contents of the user record store to it.
    	// Close the sorted user choices record store first.
    	try {
    		sortedUserChoicesTestDb.closeRecordStore();
    	}
    	catch (Exception error) {
    		alert = new Alert("Error Closing", 
    						  error.toString(), null, AlertType.WARNING); 
    		alert.setTimeout(Alert.FOREVER); 
    		display.setCurrent(alert);
    	}
    	// Then delete the sorted user record store.
    	try {
    		sortedUserChoicesTestDb.deleteRecordStore("sorteduserchoicestestfile7");
    	} catch (RecordStoreNotFoundException e) {
    		e.printStackTrace();
    	} catch (RecordStoreException e) {
    		e.printStackTrace();
    	}
    	// Then open the sorted user record store again.
    	try {
    		sortedUserChoicesTestDb = RecordStore.openRecordStore("sorteduserchoicestestfile7", true);
    	} catch (RecordStoreNotFoundException rsnfe) {
    		// Handle the exception.
    	} catch (RecordStoreFullException fsfe) {
    		// Handle the exception.
    	} catch (RecordStoreException rse) {
    		// Handle the exception.
    	}
    	
    	// Read from the user choices record store and write to the sorted user choices record store.
    	try{
    		if (userChoicesTestDb.getNumRecords() > 0) {
    			Comparator comp = new Comparator();
    			RecordEnumeration reUserChoicesEnumeration = userChoicesTestDb.enumerateRecords(null, comp, false);
    			
    			try {
    				intNumberOfSortedUserRecords = sortedUserChoicesTestDb.getNumRecords();
    			} catch (RecordStoreNotOpenException ex) {
    				ex.printStackTrace();
    			}
    			// If the sorted user choices record store does not yet have the user choices, write them to it.
    			if (intNumberOfSortedUserRecords == 0) {
    				
    				while (reUserChoicesEnumeration.hasNextElement()) {
    					//String strTheChoice = new String(reUserChoicesEnumeration.nextRecord());
    					try {
    						strTheChoice = new String(reUserChoicesEnumeration.nextRecord());
    					} catch (RecordStoreException ex) {
    						ex.printStackTrace();
    					}
    					writeRecordToSortedUserStore(strTheChoice);
    				}
    			}
    		}
    	} catch (RecordStoreNotOpenException ex) {
    		ex.printStackTrace();
    	}
    
    	// Read from the sorted user choices record store and display to the screen.
    	String strTheSortedUserChoice = null;
    	try{
    		if (sortedUserChoicesTestDb.getNumRecords() > 0) {
    			RecordEnumeration reSortedUserChoicesTestEnumeration = sortedUserChoicesTestDb.enumerateRecords(null, null, false);
    			
    			while (reSortedUserChoicesTestEnumeration.hasNextElement()) {
    				try {
    					strTheSortedUserChoice = new String(reSortedUserChoicesTestEnumeration.nextRecord());
    				} catch (RecordStoreException ex) {
    					ex.printStackTrace();
    				}
    				cgChoices.append(strTheSortedUserChoice, null);
    				System.out.println("------------------------------");
    				System.out.println("The sorted user choice: " + strTheSortedUserChoice);
    				System.out.println("------------------------------");
    			}
    		}
    	} catch (RecordStoreNotOpenException ex) {
    		ex.printStackTrace();
    	}
    	
    	screen.append(cgChoices);
    	
    	// Make the first item in the choice group be selected.
    	cgChoices.setSelectedIndex(0, true);
    	
    	intSelectedChoice = cgChoices.getSelectedIndex();
    	strSelectedIndex = Integer.toString(intSelectedChoice);
    	strSelectedChoice = cgChoices.getString(intSelectedChoice);
    	
    	// Set the current display to the screen.
    	display.setCurrent(screen);

Similar Threads

  1. Trouble with ItemStateListener and DateField
    By dergelbegeorg in forum Mobile Java Tools & SDKs
    Replies: 1
    Last Post: 2010-03-26, 16:23
  2. itemStateListener
    By cpanon in forum Mobile Java Tools & SDKs
    Replies: 2
    Last Post: 2007-09-06, 05:05
  3. ChoiceGroup & ItemStateListener
    By teoem in forum Mobile Java General
    Replies: 12
    Last Post: 2006-06-02, 08:04
  4. MIDP2.0 & itemStateListener
    By szilsan in forum Mobile Java Tools & SDKs
    Replies: 0
    Last Post: 2004-01-03, 10:07

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×