# Best way to create a hierarchy of BScreens



## perrce (Feb 8, 2007)

In the app I'm writing, I have a list that contains BScreens ready to be pushed. These BScreens in turn contain lists that contain BScreens. Repeat this for a couple levels. It didn't occur to me when I first wrote this, but I'm populating all of these lists in the constructor for each screen. So when I create the first screen, it's list is created and is populated with BScreens that contain lists, that contain BScreens that contain lists... 

In effect, when I push my first main menu screen, I'm creating all of my app's screens all at once. Using my test data it's not so bad, but with live data this could amount to thousands of BScreens in memory taking up resources.

So my question is, does a BScreen that has not been pushed take up many resources? Would I be better off populating each BScreen's list in the handleEnter() method?


----------



## s2kdave (Jan 28, 2005)

This will eventually be the cause of long start up times. You don't really want to be loading resources you aren't using. You can solve this many ways all of them involve not instantiating the BScreen until you need it. The way I did this for the main menu on my app was to have a list of Class instances, then a common constructor convention like one arg that takes the BApplication and do reflection to create the screen. Another way is to make a switch like statement to create them. Another is a factory interface mechanism that knows how to create your BScreen instance. Pick your poison.


----------



## jmose (Nov 4, 2008)

I'm having the same issue as perrce. I was building lists which were instantiating new screens that contained lists...etc. My screens are dynamic based on an XML file, and I have been running out of heap space. As the screens are dynamic, I don't think a switch statement will work, but s2kdave can you please give a quick code sample of how you create a screen using reflection or a factory interface? I have attempted to use the bananas handleEnter method to build my lists, which will not build on instantiation, but my lists are not being built at all, so I have some more debugging to do.

Thank You!


----------



## jmose (Nov 4, 2008)

I figured out a way to make it work for me, so in case anyone else runs into this issue in the future I figured I would post my solution. My screens are created dynamically based on an XML file, which can vary in length, so adding a BList to the BScreen constructor was basically preloading every single screen when the application is started. By moving the creation of the list to the handleEnter method it only loads up one level of screens at time.

create a handleEnter method in your class that is implementing BScreen.

```
public boolean handleEnter(Object arg, boolean isReturn){
    if(isReturn == false){
        BList list = new BList();
        list.add();
        setFocus(list);
    }
    return false;
}
```


----------

