0

How do i do this in Flex/Flash Builder on pageload?

This is my label:

<s:Label id="hallo" text="hallo"/>

And this is how i try to get the text value into a var:

public var halloText:String = hallo.text;

But when i run this i get an actionscript Error #1009: Cannot access a property or method of a null...

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Kevin Verhoeven
  • 179
  • 3
  • 18

1 Answers1

1

It sounds like you are trying to access the .text property before it has been instantiated.

Suppose you have an mxml file that looks like:

    <?xml version="1.0" encoding="utf-8"?>
    <test:LabelTester pageTitle="Label Test" 
    xmlns:test=".*"
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark">

        <s:Label id="hallo" text="hallo"/>

    </test:LabelTester>

and an application class called LabelTester that looks something like this:

public class LabelTester extends Application {
    public var hallo:Label;
    function LabelTester() {
        this.traceText();
    }

    private function traceText():void {
        var halloText:String = this.hallo.text;
        trace(halloText);
    }
}

Then you will get the runtime error that you describe.

But then change the constructor to this:

function LabelTester() {
//  this.traceText();
    this.addEventListener(FlexEvent.CREATION_COMPLETE, this.handleCreation);
}

and add:

private function handleCreation(creation:FlexEvent):void { this.traceText(); }

and if you run it in the debugger you should see the correct value in the console window.

Eric deRiel
  • 420
  • 3
  • 14
  • Thanks! I found a workaround already for that case, but this is more than handy for future use. – Kevin Verhoeven Dec 05 '11 at 00:01
  • I decided to get the var in the first place from somewhere else. But i would like to extend my previous question. I have posted the question here: http://stackoverflow.com/questions/8421862/flex-update-a-labels-text-wich-is-a-variable Thanks for helping me! – Kevin Verhoeven Dec 07 '11 at 20:14