tags:

views:

523

answers:

3

I have two mxml files. one is main that is application tag mxml file and another is my mxml component file. I have a viewstack in my main mxml whose id is, say, "mainViewStack". Now I want to set selectedChild property of "mainViewStack" from my mxml component file. But I m getting error: Error #1009: Cannot access a property or method of a null object reference. on accessing mainObj.mainViewStack.selectedChild.id where mainObj is the object of main mxml file. Please help me out. Thank u.

+2  A: 

My guess is that you're trying to access the child before it's created. But that's hard to tell without the code.

Try waiting until the FlexEvent.CREATION_COMPLETE event on the application to access the selected child.

Glenn
A: 

or you can give "creationPolicy=all" because Flex only creates the first visible child from the viewstack

mazgalici
A: 

This issue is referred to as "deferred instantiation" and is a product of the Flex Component Lifecycle. If you want an extremely thorough explanation of this concept, this white paper is probably the best I have read.

Essentially Flex creates components as they are needed. Each component has a lifecycle that takes it through stages:

  • Construction
  • Addition
  • Initialization
  • Invalidation
  • Validation
  • Update
  • Removal

A sub-component isn't going to be accessible until it has passed through the initialization phase. This is the point at which a Flex component will dispatch its CREATION_COMPLETE event, letting you (and the framework) know that it is ready for interaction. Prior to this event, you are going to receive null reference errors when attempting to access the component or its children.

ViewStacks compound this by default by not initializing sub-components until they are called for display. The creationPolicy property of a ViewStack, by default, is set to auto. There are several options for this property, including all. Be aware, however, that this can potentially present severe performance issues, as all of the components inside the stack are going to be initialized immediately regardless of whether or not the user actually even looks at the component.

In your specific case this isn't the problem. The component that contains the view stack hasn't been completely initialized. You need to set the child of the ViewStack in a CREATION_COMPLETE event handler.

Joel Hooks