save and load using sharedObject in AS3 - actionscript-3

i am currently doing an experiment to save each name of the user(not replacing it every time we save the new one).
my problem is the getLocal() function.I defined a variable with the type of string to make the SharedObject store the data to local storage with the name of the variable i defined which it is the name of the each user.
but i get this error:
Error #2134: Cannot create SharedObject. at
flash.net::SharedObject$/getLocal() at classes::Main/saveNewUser()
at classes::Main/promtSave()
here is my code
package classes {
import flash.display.MovieClip;
import flash.net.SharedObject;
import flash.text.TextField;
import classes.user.User;
public class Main extends MovieClip {
private var _user:User;
private var _properties:Object;
private var validOrNot_txt:TextField;
private var _name_input_txt:TextField;
//define a shared object to store our user data
private var database:SharedObject;
//define an array that will hold all users
private var userList:Array;
private var nameEntered:String;
public function Main() {
userList = [];
_name_input_txt = Name_input;
validOrNot_txt = valid_or_not_TXT;
validOrNot_txt.autoSize = 'center';
//_properties={Name:String,age:int,gender:String};
// constructor code
}
public function get user():User{
return _user;
}
private function saveNewUser():void{
nameEntered=_name_input_txt.text;
_user = new User();
_user._Name = _name_input_txt.text;
database = SharedObject.getLocal(nameEntered);
userList.push(_user);
database.data.Name = _user._Name;
}
}
}
here's the code in the timeline
import flash.events.MouseEvent;
login_btn.addEventListener(MouseEvent.CLICK, promtSave);
login_btn.buttonMode=true;
trace(Name_input.length);
function promtSave(e:MouseEvent):void{
if(Name_input.length>1){
saveNewUser();
}else{
throw(new Error('you did not enter anything'));
}
}
anybody, please help me with this :'(

Related

Why can't I access public variables from other classes?

I want to define my variables in my game document class, then use some of those variables in my Movement class. However, when I use these variables in my movement class I get tons of Compiling Errors saying that they're all undefined.
Thus my question is, why are my public variables not passed over to my other class? I have imported the class by doing import game; so this leaves me confussed. I'm probably just doing it wrong, but help is much appreciated.
Timeline
addChild((new Movement));
Game Document Class
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class game extends MovieClip
{
public var area1:Boolean = true;
public var area2:Boolean = false;
public var area3:Boolean = false;
public var player1:Boolean = true;
public var playerPosKeeper_mc:MovieClip = new mc_PlayerPosKeeper();
public var up_dpad:MovieClip = new dpad_Up();
public var down_dpad:MovieClip = new dpad_Down();
public var left_dpad:MovieClip = new dpad_Left();
public var right_dpad:MovieClip = new dpad_Right();
public var menu_dpad:MovieClip = new dpad_Menu();
public var run_dpad:MovieClip = new dpad_Menu();
public var barrierRoof1_game:MovieClip = new game_BarrierRoof();
public var barrierRoof2_game:MovieClip = new game_BarrierRoof();
public var barrierSide1_game:MovieClip = new game_BarrierSide();
public var barrierSide2_game:MovieClip = new game_BarrierSide();
public function game()
{
trace("SUCCESS | Constructed Game Class");
}
}
}
Movement Class
package
{
import game;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TouchEvent;
import flash.net.dns.AAAARecord;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Movement extends MovieClip
{
var inMotion:Boolean = false;
public function Movement()
{
trace("SUCCESS | Constructed Movement Class");
addChild(playerPosKeeper_mc);
playerPosKeeper_mc.x = 384;
playerPosKeeper_mc.y = 46;
addChild(up_dpad);
up_dpad.x = 55;
up_dpad.y = 336;
addChild(down_dpad);
down_dpad.x = 57;
down_dpad.y = 432;
addChild(left_dpad);
left_dpad.x = 19;
left_dpad.y = 372;
addChild(right_dpad);
right_dpad.x = 118;
right_dpad.y = 372;
addChild(menu_dpad);
menu_dpad.x = 61;
menu_dpad.y = 377;
addChild(run_dpad);
run_dpad.x = 684;
run_dpad.y = 369;
addChild(barrierRoof1_game);
barrierRoof1_game.x = 0;
barrierRoof1_game.y = 0;
addChild(barrierRoof2_game);
barrierRoof2_game.x = 0;
barrierRoof2_game.y = 470;
addChild(barrierSide1_game);
barrierSide1_game.x = 0;
barrierSide1_game.y = 0;
addChild(barrierSide2_game);
barrierSide2_game.x = 790;
barrierSide2_game.y = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
up_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, moveUpTouchBEGIN);
up_dpad.addEventListener(TouchEvent.TOUCH_END, moveUpTouchEND);
}
public function moveUpTouchBEGIN(e:TouchEvent):void
{
trace("Touch Began")
}
public function moveUpTouchEND(e:TouchEvent):void
{
trace("Touch Ended")
}
}
}
You are confused because "public" does not mean "global". Declaring variable as public means you want to grant an access to it to any entity, given the entity knows where that variable is.
Lets see what you have there.
Top display object: stage.
Main timeline: game is a child of stage.
MovieClips up_dpad, down_dpad and so on, all are fields of the game instance.
Movement: instance is a child of game.
In the Movement you are trying to access up_dpad and others, but they are kept as fields of game instance and have nothing to do with the Movement instance. That's why they are outside of Movement's addressing context.
So, if you want to have these variables declared as game fields, you need to address them from the Movement in a correct way.
Forget the timeline. In the Game (for the sake's sake never call classes in lowercase unless at the gunpoint) which is, I believe, a root document class:
public function Game()
{
trace("SUCCESS | Constructed Game Class");
// Pass reference to this instance to the constructor.
var aMove:Movement = new Movement(this);
// Add it as a child.
addChild(aMove);
}
In Movement:
public function Movement(main:Game)
{
trace("SUCCESS | Constructed Movement Class");
// Access variables inside Game instance via given reference.
addChild(main.playerPosKeeper_mc);
main.playerPosKeeper_mc.x = 384;
main.playerPosKeeper_mc.y = 46;
// ...and so on
}
These are basics of Object Oriented Programming. If you want to access anything inside an object, you need to access the object first.

AS3: 1180 Call to a possibly undefined property: Add Child

Pretty big noob at AS3. I'm trying to Load a SWF into another file. (Main .fla loading external SWFS on mouse click)
I keep getting the error: 1180 Call to a possibly undefined property: Add Child, however.
My LoadSWF code is:
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class LoadSWF {
private var loaderFile: Loader;
private var swfFile: Object;
private var sourceFile: String;
private var fileLabel: String;
private var canDrag: Boolean;
private var popX: int;
private var popY: int;
public function LoadSWF(myFile: String, myLabel: String, myX: int = 0, myY: int = 0, myDrag: Boolean = false) {
// constructor code
trace("Loading SWF file:", myFile);
sourceFile = myFile;
fileLabel = myLabel;
canDrag = myDrag;
popX = myX;
popY = myY;
openSWF();
}
private function openSWF(): void {
// initialise variables
loaderFile = new Loader();
swfFile = addChild(loaderFile);
// set initial position of the SWF popup
loaderFile.x = popX;
loaderFile.y = popY;
try {
loaderFile.load(new URLRequest(sourceFile));
// runs after the SWF popup has finished loading
loaderFile.contentLoaderInfo.addEventListener(Event.COMPLETE, SWFloaded);
} catch (err: Error) {
// provide some error messages to help with debugging
trace("Error loading requested document:", sourceFile);
trace("Error:", err);
sourceFile = null;
}
} //end openSWF
private function SWFloaded(evt: Event): void {
// and add the required event listeners
loaderFile.addEventListener(MouseEvent.MOUSE_DOWN, dragSWF);
loaderFile.addEventListener(MouseEvent.MOUSE_UP, dropSWF);
// use the POPUP reference to access MovieClip content
swfFile.content.gotoAndStop(fileLabel);
// assigns a close function to the button inside the popup
swfFile.content.closeBtn.addEventListener(MouseEvent.CLICK, closeSWF);
// remove the COMPLETE event listener as it’s no longer needed
loaderFile.contentLoaderInfo.removeEventListener(Event.COMPLETE, SWFloaded);
} //end SWFLOaded
private function dragSWF(evt: MouseEvent): void {
swfFile.content.startDrag();
}
private function dropSWF(evt: MouseEvent): void {
swfFile.content.stopDrag();
}
private function closeSWF(evt: MouseEvent): void {
// remove the required event listeners first
loaderFile.removeEventListener(MouseEvent.MOUSE_DOWN, dragSWF);
loaderFile.removeEventListener(MouseEvent.MOUSE_UP, dropSWF);
swfFile.content.closeBtn.removeEventListener(MouseEvent.CLICK, closeSWF);
// remove the pop-up
loaderFile.unloadAndStop();
}
} //end class
} //end package
I'm calling it into my main class file, which code is (I left out the rest, guessing its unnecessary):
package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.display.SimpleButton;
import flash.utils.Dictionary;
import flash.text.TextFormat;
import flash.net.*;
import flash.events.*;
import fl.controls.*;
import flash.media.*;
import fl.events.ComponentEvent;
import fl.managers.StyleManager;
import fl.data.DataProvider;
import fl.data.SimpleCollectionItem;
import fl.managers.StyleManager;
import fl.events.ComponentEvent;
import flash.events.Event;
import flash.net.SharedObject;
import LoadSWF;
public class Main extends MovieClip {
//Declare variables
private var componentFmt: TextFormat;
private var radioBtnFmt: TextFormat;
private var playerData: Object;
private var savedGameData: SharedObject;
// Pop-up Variables
private var popupFile: LoadSWF;
private var swfPath: String;
public function Main() {
// constructor code
this.savedGameData = SharedObject.getLocal("savedPlayerData");
this.setComponents();
this.setPlayerData();
//this.swfPath = "";
//this.isHelpOpen = false;
//this.sndPath = "musicSFX/music2.mp3";
//this.isMuted = false;
//this.sndTrack = new LoadSND(this.sndPath, this.canRepeat);;
//this.muteBtn.addEventListener(MouseEvent.CLICK, this.setMute);
swfPath = "";
helpBtn.addEventListener(MouseEvent.CLICK, openSWF);
//hauntedForestBtn.addEventListener(MouseEvent.CLICK, openSWF);
}
public function openSWF(evt: MouseEvent): void {
// determine which button was pressed
var myFile: String = evt.currentTarget.name.replace("Btn", ".swf");
myFile = (swfPath == "") ? myFile : swfPath + myFile;
if (myFile == "help.swf") {
// load the help SWF file - is draggable
swfFile = new LoadSWF(myFile, currentFrameLabel, 80, 60, true);
} else {
// load the selected SWF file - is not draggable
swfFile = new LoadSWF(myFile, currentFrameLabel);
}
addChild(swfFile);
}
If anyone could help me find a solution, i'd greatly appreciate it.
Thanks :)
addChild is defined by DisplayObjectContainer.
So to access this function, you'll have to alter LoadSWF so that it extends DisplayObjectContainer.

AS3 public variable won't store values

first time poster here.
So I'm building a "multi-RSS feed reader" and I've broken this into 2 classes, a "TechFeed.as" and a "Feed.as"; The tech feed instantiates multiple feeds by passing URL's to a new Feed object.
My issue at the moment is that in the Feed.as I have a couple public variables which are used in TechFeed.as to display basic details about the feed, however, these variables refuse to retain any value I give them within Feed.as's functions, and are turning up "null".
Edit: Also maybe something to note; TechFeed.as is the main AS file the stage uses.
TechFeed.as
package {
import flash.display.MovieClip;
public class TechFeed extends MovieClip {
private var feed_one:Feed = new Feed("http://feeds.feedburner.com/crunchgear");
private var feed_two:Feed = new Feed("http://feeds.mashable.com/Mashable");
private var feed_three:Feed = new Feed("http://www.engadget.com/rss.xml");
public function TechFeed() {
trace(feed_one.feed_title);
//feed_name.text = feed_one.getFeedTitle();
}
}
}
Feed.as
package {
import flash.net.URLLoader;
import flash.events.Event;
import flash.net.URLRequest;
public class Feed {
//Public variables to display feed info
public var feed_title:XMLList;
public var feed_desc:String;
public var feed_link:String;
//Setting up variables which help load the feeds
private var feedXML:XML;
//Create a loader to load an external URL
private var loader:URLLoader = new URLLoader();
public function Feed(inURL:String = "") {
//Load the xml document
loader.load(new URLRequest(inURL));
loader.addEventListener(Event.COMPLETE,onLoaded);
}
//When the loader had loaded the xml document, pass that into a variable for use.
private function onLoaded(e:Event):void {
feedXML = new XML(e.target.data);
// break down the xml document elements into singular XML array lists
//Feed details
this.feed_title = feedXML.channel.title;
this.feed_link = feedXML.channel.link;
this.feed_desc = feedXML.channel.description;
trace(this.feed_title);
}
}
}
Any help will be greatly appreciated :)
Thanks,
Geoff
Your problem is timing you are trying to write the data from the feed before it is returned from the server.
In this example I assign a function to call back on when the data is loaded.
package {
import flash.display.MovieClip;
public class TechFeed extends MovieClip {
private var feed_one:Feed;
private var feed_two:Feed;
private var feed_three:Feed;
public function TechFeed() {
feed_one= new Feed("http://feeds.feedburner.com/crunchgear",assignResults);
feed_two= new Feed("http://feeds.mashable.com/Mashable",assignResults);
feed_three= new Feed("http://www.engadget.com/rss.xml",assignResults);
}
public function assignResults(value:value):void{
feed_name.text = value;
}
}
}
package {
import flash.net.URLLoader;
import flash.events.Event;
import flash.net.URLRequest;
public class Feed {
//Public variables to display feed info
public var feed_title:XMLList;
public var feed_desc:String;
public var feed_link:String;
//Setting up variables which help load the feeds
private var feedXML:XML;
//Create a loader to load an external URL
private var loader:URLLoader = new URLLoader();
private var _callBackFunc:Function;
public function Feed(inURL:String = "", callBackFunc:Function) {
this._callBackFunc = callBackFunc;
//Load the xml document
loader.load(new URLRequest(inURL));
loader.addEventListener(Event.COMPLETE,onLoaded);
}
//When the loader had loaded the xml document, pass that into a variable for use.
private function onLoaded(e:Event):void {
feedXML = new XML(e.target.data);
// break down the xml document elements into singular XML array lists
//Feed details
this.feed_title = feedXML.channel.title;
this.feed_link = feedXML.channel.link;
this.feed_desc = feedXML.channel.description;
this._callBackFunc(this.feed_title);
}
}
}
If the problem is that feed_one.feed_title is coming up null in the TechFeed() ctor, that is because you are not waiting for the feed to finish loading.
What you aught to do is dispatch an event from the Feed when it is done loading and processing the data, catch it in TechFeed and then use the public variables as you please (this also means that your Feed class will have to subclass EventDispatcher):
In Feed class:
private function onLoaded(e:Event):void {
feedXML = new XML(e.target.data);
// break down the xml document elements into singular XML array lists
//Feed details
this.feed_title = feedXML.channel.title;
this.feed_link = feedXML.channel.link;
this.feed_desc = feedXML.channel.description;
trace(this.feed_title);
dispatchEvent(new Event(Event.COMPLETE));////Dispatch Event
}
In TechFeed class:
public function TechFeed() {
trace(feed_one.feed_title);//This will trace "null"
feed_one.addEventListener(Event.COMPLETE, dataLoaded);//add event listener
}
private function dataLoaded(e:Event):void{
var feed = Feed(e.currentTarget);
feed.removeEventListener(Event.COMPLETE, dataLoaded);//remove event listener to prevent memory leaks
trace(feed.feed_title);// This will trace the correct title
}

Error #1034, with a MouseEvent

I am making a basic point n' click game and I came upon this error:
TypeError: Error #1034: Type Coercion failed: cannot convert 3 to cem.mouvement.
Here's my script:
package cem {
import flash.events.Event;
import flash.display.MovieClip;
import cem.microjeux.events.InfoJeuEvent;
import cem.mouvement;
import flash.events.MouseEvent;
public class monterJeu extends MovieClip
{
private static var pType:String = "type";
private static var pNom:String = "testNom";
private static var pCourriel:String = "test#hotmail.com";
private static var pDifficulte:int = 0;
private static var pLangue:int = 0;
private static var pTitre:String = "Veuillez sortir";
private static var pVersion:String = "1.5";
private static var pCoordonnees:Number;
private var environnementJeu:environnement = new environnement();
private var personnageJeu:personnage = new personnage();
public function monterJeu():void
{
jouer(pNom,pDifficulte,pLangue);
dispatchEvent(new InfoJeuEvent(pType,pNom,pCourriel,pTitre,pVersion));
stage.addEventListener(MouseEvent.CLICK, test);
}
public function jouer(PNom:String,PDifficulte:int,PLangue:int):void
{
addChild(environnementJeu);
addChild(personnageJeu);
}
function test(e:MouseEvent){
pCoordonnees = stage.mouseX;
trace(pCoordonnees);
mouvement(3);
}
}
}
And on mouvement();
package cem
{
public class mouvement {
public function mouvement(blabla) {
trace(blabla);
}
}
}
I searched everywhere I could, and didn't find anything. I have no instances on the stage. Everything is imported on the first frame. I am kind of a beginner (let's say i'm no good at programming), so you can notify at the same time if you something that needs to be corrected. (BTW, the strange words are in french ;D)
Thanks!
The error is due to you trying to cast 3 to mouvement.
I think what you want is something like
function test(e:MouseEvent){
pCoordonnees = stage.mouseX;
trace(pCoordonnees);
var mouve:mouvement = new mouvement(3);
}
Notice that you have to have new in order to create a new instance of a class.
On another note, you should capitilize classes so they stand out better. So I would name the class Mouvement.
You are trying to cast 3 to the class mouvement into the test function:
function test(e:MouseEvent){
pCoordonnees = stage.mouseX;
trace(pCoordonnees);
new mouvement().mouvement(3); // <-- here your error
}
If you have only a function into your class you don't need to create a class but you can put on the function alone:
package cem
{
public function mouvement(blabla):void {
trace(blabla);
}
}
and now you can call the mpuvement function normally into you test function:
function test(e:MouseEvent){
pCoordonnees = stage.mouseX;
trace(pCoordonnees);
mouvement(3);
}

AS 3.0 reference problem

I am finding it hard to fugure out the reference system in AS 3.0.
this is the code i have (i have trimmed it down in order to find the problem but to no avail)
package rpflash.ui {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Stage;
import nowplaying;
import flash.text.TextField;
public class RPUserInterface extends Sprite{
var np:nowplaying;
public function RPUserInterface(){
}
public function init(){
var np:nowplaying = new nowplaying();
this.addChild(np)
}
public function updateplayer(xml:XML){
var artist: String = xml.nowplaying.artist.toString();
var title: String = xml.nowplaying.title.toString();
trace("UI:update");
trace(this.np);// this gives me a null reference
}
}
}
and still i cannot access np!!! trace this.np gives me a null reference. i am not even trying to access it from a subling class. (btw i def want to know how to do that as well.)
In your init() function, you are instantiating a local variable called np. Try this instead:
public function init() {
// var np:nowplaying = new nowplaying();
np = new nowplaying();
this.addChild(np);
}
Also, make sure init() is getting called before updateplayer(). Hope that helps.