java-melcdui

j2me - Does a List have any property to keep track of 'key' that identify the item


How do you usually deal with Lists and the fact that they don't have a property to clearly identity an specific item ? So far, the only solucion I could come up with is to put the key I use at the beginning, followed by a hyphen and the text that is shown on every item. This way when I retrieve the text from the selected item I can get the key for the item.

This is how I do it, but surely there's gotta be a better solution and I'd really like that you could share your experience in this kind of scenarios.

Thanks in advance.

enter image description here


Solution

  • The picture ooks like you keep all the data managed in your application inside the text of the items of a standard list.

    Better hava a separate class for the data container objects and an overview screen derived from List that takes an array of those container objects and instantiate the Items from that. This screen could then provide a method

    DataContainer getSelectedObject()
    

    which uses getSelectedIndex() internally to look up the object.

    More specifically (Overview.java)

    package mvc.midlet;
    
    import javax.microedition.lcdui.List;
    
    public class Overview extends List {
    
        private final DomainObject[] data;
        public static Overview create(DomainObject[] data) {
            int i = 0;
            for(; i < data.length; i++) {
                if(data[i] == null) break;
            }
            String[] names = new String[i];
            for(int j = 0; j < i; j++) {
                names[j] = data[j].name;
            }
            return new Overview(names, data);
        }
    
        protected Overview(String names[], DomainObject[] data) {
            super("Overview", IMPLICIT, names, null);
            this.data = data;
        }
    
        public DomainObject getSelectedObject() {
            return data[this.getSelectedIndex()];
        }
    }