Search code examples
blackberryblackberry-simulatorblackberry-eclipse-pluginblackberry-jde

How to attach and get particular list item id in BlackBerry?


I am trying to create lists using FieldManagers (Horizontal and Vertical). In this list I have multiple clickable items like buttons, so I am not using ListField or ObjectListField.

I have successfully created the UI, but I am unable to attach a particular item id coming from the server. Also, on clicking a particular button in any list row, I want to get the item id and want to perform an action against that ID.

So, please let me know the idea how I can attach the id to a particular row while I am using FieldManager and then how I can generate event against that ID on clicking a button?


Solution

  • When you create a row, you are probably creating a (subclass of) Manager for each row.

    At least, it seems like you are creating a ButtonField on each row.

    What you can do is to attach a cookie to each row, or to each button, when you create it. A cookie is just an extra piece of information that's attached to an object. Then, when that row or button is clicked, you ask the row/button for the cookie, and use that to identify the row ID.

    Every BlackBerry Field can have a cookie attached to it. Since the cookie is of type Object, you can make it anything you want.

    For example, when creating the buttons for your rows:

    for (int i = 0; i < numRows; i++) {
        BitmapButtonField button = new BitmapButtonField(onImage, offImage, ButtonField.CONSUME_CLICK);
        // use the row index as the cookie
        button.setCookie(new Integer(i));
        button.setChangeListener(this);
        Manager row = new MyRowManager();
        row.add(button);
        add(row);
    }
    

    and then when the button is clicked:

    void fieldChanged(Field field, int context) {
        Object cookie = field.getCookie();
        if (cookie instanceof Integer) {
            Integer rowId = (Integer)cookie;
            System.out.println("Row Id = " + rowId);
        }
    }
    

    Note: I'm using the BlackBerry Advanced UI BitmapButtonField for this, but the cookie technique will work with any Field, or Manager class. See another example here.