as3 use setter in other class(parent) - actionscript-3

I'm trying to make a simple setter which i like to access with a child class.
Here is the parent class code :
public class DeGeheimeMissie extends MovieClip
{
var deLader:URLLoader;
var deXmlData:XML;
public var hoofdVragenLijst:Object = new Object();
public var subVragenLijst:Object = new Object();
public var hetAntwoord:String;
public function DeGeheimeMissie()
{
var hetVerzoek:URLRequest;
hetVerzoek = new URLRequest("dialogen.xml");
deLader = new URLLoader(hetVerzoek);
deLader.addEventListener(Event.COMPLETE, vragenGeladen);
deLader.load(hetVerzoek);
instObama.addEventListener(MouseEvent.CLICK, showVragen);
instObama.buttonMode = true;
instObama.useHandCursor = true;
}
public function set hetAntw(str:String):void
{
hetAntwoord = str;
}
and here is the child class where i try to access it:
public class Rutte extends MovieClip
{
var deLader:URLLoader;
var deXmlData:XML;
public var antwoordenOverzicht = [];
//constructor
public function Rutte()
{
var hetVerzoek:URLRequest;
hetVerzoek = new URLRequest("dialogen.xml");
deLader = new URLLoader(hetVerzoek);
deLader.addEventListener(Event.COMPLETE, antwoordenGeladen);
deLader.load(hetVerzoek);
instRutte.addEventListener(MouseEvent.CLICK, showAntwoorden);
instRutte.buttonMode = true;
instRutte.useHandCursor = true;
}
public function setAntwoord(e:MouseEvent)
{
var antw = e.currentTarget.text.charAt(0);
trace(e.currentTarget.text.charAt(0));
this.parent.hetAntw(antw);
}
The error i get here is:
1061: Call to a possibly undefined method hetAntwoord through a reference with static type flash.display:DisplayObjectContainer.

You should try this, this is how we use setters :
this.parent.hetAntw = antw;
But why making a public setter on a public static var ?

Related

AS3 - Error #1009: Cannot access a property or method of a null object reference

I have no idea what is causing the error. I'm sure its very obvious.
(See comments below).
package src.main{
import src.tilespack.Tile;
public class Main{
public var tile:Tile;
public function Main{
var t:Tile = Tile.tiles[0]; //Error here
trace(Tile); //This will also cause an error
}
Tile:
package src.tilespack{
public static var tiles:Array = [];
public static var floorTile:Tile = new FloorTile(0); //Causes an error in FloorTile Class
public var bitmapData:BitmapData;
public function Tile(bitmapData:BitmapData, ID:int)
{
this.ID = ID;
tiles[ID] = this;
this.bitmapData = bitmapData;
}
}
FloorTile:
package src.tilespack{
import src.gfx.Assets;
import src.tilespack.Tile;
public class FloorTile extends Tile{ //Error here
public function FloorTile(ID:int){
super(Assets.floorTileData, ID);
}
}
}
Error #1009: Cannot access a property or method of a null object
reference.
I've noticed few problems in your code:
1) The file Tile doesn't have a definition of class. Probably, this is just a typo, but anyway, this file should look something like:
package src.tilespack
{
public class Tile
{
public static var tiles:Array = [];
public static var floorTile:Tile = new FloorTile(0); //Causes an error in FloorTile Class
public var ID:int;
public var bitmapData:BitmapData;
public function Tile(bitmapData:BitmapData, ID:int)
{
this.ID = ID;
tiles[ID] = this;
this.bitmapData = bitmapData;
}
}
}
2) Your code has something like "recursive linkage" (sorry, I don't know the official term). Your class Tile has the static variable floorTile, and it tries to create an instance of the FloorTile class, which itself extends the class Tile.
So we have a situation, when the class Tile tries to use the class FloorTile (because static variables should be instantiated during the first class use), and the class FloorTile tries to use the class Tile. And it's a problem.
You may either remove static variable of the type FloorTile or change code of the class Tile to prevent usage of the class FloorTile before the class Tile is prepared to work. Here an example of the second approach:
package src.tilespack
{
import flash.display.BitmapData;
public class Tile
{
public static var tiles:Array = [];
private static var _floorTile:Tile;
public static function get floorTile():Tile
{
if (!Tile._floorTile)
{
Tile._floorTile = new FloorTile(0);
}
return Tile._floorTile;
}
public var ID:int;
public var bitmapData:BitmapData;
public function Tile(bitmapData:BitmapData, ID:int)
{
this.ID = ID;
tiles[ID] = this;
this.bitmapData = bitmapData;
}
}
}

AS3 Can't get array from another class

Well, I have a problem, with searching changes of array in ItemProperty class. When i calling to trace item array length, than it gets 0. But in ItemProperty class only in RecieveIndex function item length getting more than 2. Even ReturnData() got 0. The question is how to get final result of this array(Item) in InventoryData class?
That is class, when i got 0:
public class InventoryData extends Sprite {
private var item:ItemProperty = new ItemProperty();
public function InventoryData(){
trace(item.Item);
trace(item.Item.length);
//trace(item.ReturnData());
}
}
Class where array was formed. In RecieveIndex method Item length more than 0.
public class ItemProperty extends Sprite{
public var Item:Array = [];
public function ItemProperty() {
var connect:Connection = new Connection();
connect.setRequest("Select", "`inventory`", ["all"], ["all"], InventoryContent);
}
private function InventoryContent(RecieveData:Array):void
{
var picking:Connection = new Connection();
picking.setRequest("Select","`weapon`",["all"],["id IN("+RecieveData[0].contents.toString() + ")"], InventotyData);
}
private function InventotyData(RecieveData:Array):void{
var indexdecode:Connection = new Connection();
for(var i:uint=0; i<RecieveData.length; i++)
{
indexdecode.loadImageFromBase64(RecieveData[i].id, RecieveIndex);
}
}
public function RecieveIndex(index:int):void {Item.push(index); }
public function ReturnData():Array {return Item;}
}
Something like this with the event I mentioned in my comment:
public class InventoryData extends Sprite {
private var item:ItemProperty = new ItemProperty();
public function InventoryData(){
item.addEventListener(ItemProperty.ARRAY_READY, onArrayReady);
}
private function onArrayReady(e:Event):void {
trace(item.Item.length);
}
}
In ItemProperty class you declare a new constant:
public static const ARRAY_READY:String = "arrayReady";
and once you have the array filled with the items you want to retrieve, you add:
dispatchEvent(new Event(ARRAY_READY));

AS3 TypedDictionary?

public dynamic class TypedDictionary extends Dictionary {
private var _type:Class;
public function TypedDictionary(type:Class, weakKeys:Boolean = false) {
_type = type;
super(weakKeys);
}
public function addValue(key:Object, value:_type):void {
this[key] = value;
}
public function getValue(key:Object):_type{
return this[key];
}
...
I want to make TypedDictionary with typisation. But I can not use _type in addValue and getValue. The idea is to use next construction :
var td:TypedDictionary = new TypedDictionary(myClass, true);
td.addValue("first", new myClass());
...
var item:myClass = td.getValue("first");
item.someFunction();
Is any ability to use dynamic class type?
If I un derstand what you are asking for.
This is untested code so it could be error prone, but it should get you on the right path.
public dynamic class TypedDictionary extends Dictionary {
private var _type:Class;
public function TypedDictionary(type:String, weakKeys:Boolean = false) {
_type = getDefinitionByName(type) as Class;
super(weakKeys);
}
public function addValue(key:Object, value:*):void {
if(_type == getDefinitionByName(getQualifiedClassName(value))){
this[key] = value;
}else{
trace('failed type match')
}
}
public function getValue(key:Object):*{
return this[key];
}
...
var td:TypedDictionary = new TypedDictionary("com.somepackage.myClass", true);
td.addValue("first", new myClass());
var item:myClass = td.getValue("first");
item.someFunction();

Flex - Cursor search in ArrayCollection not working

So I'm following the book Adobe Flex 4 Training From the Source by Michael Labriola, Jeff Tapper and Matthew Boles, for context.
I'm building a Shopping Cart Class that recieves a ShoppingCartItem object (which is just a POAO) from the mxml and adds it to an ArrayCollection via this public function:
private var $items:ArrayCollection = new ArrayCollection();
public function addItem(item:ShoppingCartItem):void
{
var inCart:Boolean = false;
var currentItem:ShoppingCartItem;
for(var i:int = 0; i < $items.length; i++)
{
currentItem = $items.getItemAt(i) as ShoppingCartItem;
if(item.$product == currentItem.$product)
{
inCart = true;
break;
}
}
if(inCart)
{
currentItem.$quantity++;
}
else
{
$items.addItem(item);
}
updateTotal();
$items.refresh();
}
According to the book, the same function can be achieved with an IViewCursor, like this.
public function addItem(item:ShoppingCartItem):void
{
var cursor:IViewCursor = $items.createCursor();
var inCart:Boolean = cursor.findFirst(item);
if(inCart)
{
var existing:ShoppingCartItem = cursor.current as ShoppingCartItem;
existing.$quantity++;
}
else
{
$items.addItem(item)
}
}
Problem is, when I use this function the item quantity is never updated. Then I have a Shopping cart with 2 entries of 1 product when I should have 1 entry of 2 products. Tracing the inCart boolean yields "false", no matter what I do. The first function works properly and as expected, so I have no idea why the data is not being updated correctly. Also, if I call $items.refresh(); at the end of the second function (for sorting), it throws a NullPointerException error.
Another thing to notice is that I'm using a book for Flex 4 when I'm using the 4.6.0. SDK, the last Adobe release before it was gifted to Apache. I don't know if this is of any importance.
Here's the code for ShoppingCartItem:
[Bindable]
public class ShoppingCartItem
{
public var $product:Product;
public var $quantity:uint;
public var $subtotal:Number;
public function getSubTotal():Number
{
calculateSubTotal();
return $subtotal;
}
public function toString():String
{
return "[ShoppingCartItem]"+$product.prodName+":"+$quantity;
}
public function calculateSubTotal():void
{
this.$subtotal = $product.listPrice*$quantity;
}
public function squeak():void
{
trace("squeak");
}
public function ShoppingCartItem(product:Product, quantity:uint = 1)
{
this.$product = product;
this.$quantity = quantity;
calculateSubTotal();
}
EDIT: More information request by Sunil D.
Product.as class:
[Bindable]
public class Product
{
public var catID:Number;
public var prodName:String;
public var unitID:Number;
public var cost:Number;
public var listPrice:Number;
public var description:String;
public var isOrganic:Boolean;
public var isLowFat:Boolean;
public var imageName:String;
public function toString():String
{
return "[Product]"+this.prodName;
}
public static function buildProductFromAttributes(data:XML):Product
{
var p:Product;
var isOrganic:Boolean = (data.#isOrganic == "Yes");
var isLowFat:Boolean = (data.#isLowFat == "Yes");
p = new Product(data.#catID,
data.#prodName,
data.#unitID,
data.#cost,
data.#listPrice,
data.#description,
isOrganic,
isLowFat,
data.#imageName);
return p;
}
public static function buildProduct(o:Object):Product
{
var p:Product;
p = new Product(o.catId,o.prodName,o.unitID,o.cost,o.listPrice,
o.description,(o.isOrganic == 'true'),
(o.isLowFat == 'true'),o.imageName);
return p;
}
public function Product(cid:Number, name:String, uid:Number, cost:Number, listp:Number, desc:String, iso:Boolean, ilf:Boolean, imn:String)
{
this.catID = cid;
this.prodName = name;
this.unitID = uid;
this.cost = cost;
this.listPrice = listp;
this.description = desc;
this.isOrganic = iso;
this.isLowFat = ilf;
this.imageName = imn;
}
}
ArrayCollection sorting sortfield is the Product POAO contained in the ShoppingCartItem Class. It's done within the constructor function of ShoppingCart like this:
public class ShoppingCart
{
[Bindable]
private var $items:ArrayCollection = new ArrayCollection();
public function ShoppingCart()
{
var prodSort:Sort = new Sort();
var sortField:SortField = new SortField("product");
prodSort.fields =[sortField];
$items.sort = prodSort;
$items.refresh();
}
The reason the viewcursor approach is not working is because the item (ShoppingCartItem) is not in the $items collection. This method compares object references and will hence not find your item if it is another instance of ShoppingCartItem.
In the first approach you are not comparing object references of ShoppingCartItem, but comparing the "product" property of the items.

how to to assign a parent's variable from the parent's child?

i want to pass the variable from parent to child .How Can i pass the Variable.Here i paste my code.AnyBody please guide me.Thanks in advance!
My Parent Class
public class PlayerStrobe_domaincheck extends Sprite
{
private var myService:NetConnection = new NetConnection();
private var _loader:Loader;
public function PlayerStrobe_domaincheck()
{
_loader = new Loader();
var sourceId:String = loaderInfo.parameters.src;// I want to pass This Variable
var some:StrobeMediaPlayback = new StrobeMediaPlayback(parentObject);// Access of undefined property parentObject(Error Message).
some = new StrobeMediaPlayback(this);
}
}
My Child Class
public class StrobeMediaPlayback extends Sprite
{
private var _loader:Loader;
private var sourceId:String; //i want to access the the parent variable(sourceId) here
parentClass = parent;
function Test():void
{
mediaContainer.addMediaElement(alert);
alert.alert("Error",parentClass.sourceId);
}
public class PlayerStrobe_domaincheck extends Sprite
{
private var myService:NetConnection = new NetConnection();
private var _loader:Loader;
public function PlayerStrobe_domaincheck()
{
_loader = new Loader();
var sourceId:String = loaderInfo.parameters.src;
var some:StrobeMediaPlayback = new StrobeMediaPlayback(sourceId);
new StrobeMediaPlayback(this);
}
}
public class StrobeMediaPlayback extends Sprite
{
private var _loader:Loader;
private var sourceId:String;
parentClass = parent;
public function StrobeMediaPlayback(sourceIdVariablePassed:String):void
{
mediaContainer.addMediaElement(alert);
trace("Source ID "+sourceIdVariablePassed);
}
}
You can not directly do it unless your variable in the parent is public
Then again, it is not really good code to do that, because then the child is constrained to be added to only your parent class and nothing else.
The best way would be to dispatch an event, and have the parent listen to that event. The event handler in the parent should change the variable in the parent.
Yoc can pass parent to child class
public class StrobeMediaPlayback extends Sprite
{
private var _loader:Loader;
private var sourceId:String; //i want to access the the parent variable(sourceId) here
private var parentClass:PlayerStrobe_domaincheck;
public function StrobeMediaPlayback(parent:PlayerStrobe_domaincheck)
{
parentClass = parent;
trace("welcome");
}
public function Test():void
{
trace(parentClass.sourceId);
}
}
and when you construct your child from parent (for example) pass parent object as param like
var some:StrobeMediaPlayback = new StrobeMediaPlayback(parentObject)
and you definition of parent should be like this
public class PlayerStrobe_domaincheck extends Sprite
{
private var myService:NetConnection = new NetConnection();
private var _loader:Loader;
private var some:StrobeMediaPlayback; //update
public var sourceId:String;
public function PlayerStrobe_domaincheck()
{
_loader = new Loader();
sourceId = loaderInfo.parameters.src;// I want to pass This Variable
some = new StrobeMediaPlayback(this) //update
}
}
you can defile your child object in parents constructor