Putting Loader in a custom class: events, returning to main ... asynch challenges

I'm creating a custom class to retrieve some data using URLoader.
My code is below, doing this from memory, plz ignore any minor typos.
The challenge I'm encountering: when my custom class calls the loader, the event handler takes over.  At which point the context of my code leaves the function and it's not clear to me how I then return the data retrieved by the loader.  I sense that I'm breaking the rules of how ActionScript really runs by putting a loader in a separate class; at least, that's my primitive understanding based upon the reading I've done on this.
So can I do this?  I am trying to create a clean separation of concerns in my program so that my main program doesn't get clogged up with code concerned with retrieving remote data.
Thanks!
Main program;
import bethesda.myLoader;
var ldr:myLoader = new myLoader;
var data:String = myLoader.getData("someurl");
My custom class:
package bethesda {
     public class myLoader {
          function myLoader(url:String):String {
               var loader:URLLoader = new URLLoader();
               var request:URLRequest = new URLRequest(url);
               loader.addEventListener(Event.COMPLETE, completeHandler);
     function completeHandler(event:Event):void {
          var ld:URLLoader = new URLLoader(event.target);
          data = loader.load(); // here's where I don't know what to do to get the data back to my main program

I think you are on the right track in abstracting loading from other code.
Your class may be like that:
package 
     import flash.events.Event;
     import flash.events.EventDispatcher;
     import flash.net.URLLoader;
     import flash.net.URLRequest;
     public class myLoader extends EventDispatcher
          // declare varaibles in the header
          private var loader:URLLoader;
          private var url:String;
          public function myLoader(url:String)
              this.url = url;
          public function load():void {
              var loader:URLLoader = new URLLoader();
              var request:URLRequest = new URLRequest(url);
              loader.addEventListener(Event.COMPLETE, completeHandler);
              loader.load(request);
          private function completeHandler(e:Event):void
              dispatchEvent(new Event(Event.COMPLETE));
          public function get data():*{
              return loader.data;
Although, perhaps the best thing to do would be to make this class extend URLLoader. With the example above you can use the class as following:
import bethesda.myLoader;
import flash.events.Event;
var ldr:myLoader = new myLoader("someurl");
ldr.addEventListener(Event.COMPLETE, onLoadComplete);
ldr.load();
function onLoadComplete(e:Event):void {
     var data:String = ldr.data;

Similar Messages

  • Loading resources with customized class loader

    I have a customized classloader that keeps classes and resources in a table in byte[] form. It works fine as far as loading classes go, I just call defineClass with the byte array corresponding to the class. My problem is how to load resources. I already have the resource data in the table, which you'd think would be a good thing, but the method that has to be overridden (getResource or findResource) is supposed to return an URL to the resource. The only way I can think of to do that is to write the data to a file and return an URL to that file, but I don't even wanna touch that solution with a nine foot stick. Surely there must be a better way!?

    Usually, when your resources are in a custom source, you create and implement your own URL protocol (like jar:). This is done by creating your own java.net.URLStreamHandler and java.net.URLConnection implementations. You can peruse the jar implementation in sun.net.www.protocol.jar as a good example.
    Once you have your own protocol that knows how to get to your resource file and how to identify and extract a resource, you simply use that protocol in the URLs returned by your ClassLoader. The resource URLs can then be used as you would normally use any URL.
    A tutorial describing how all of this works, and how to implement your own is at:
    http://developer.java.sun.com/developer/onlineTraining/protocolhandlers/
    I hope you find this of some help.

  • Custom class loader and local class accessing local variable

    I have written my own class loader to solve a specific problem. It
    seemed to work very well, but then I started noticing strange errors in
    the log output. Here is an example. Some of the names are in Norwegian,
    but they are not important to this discussion. JavaNotis.Oppstart is the
    name of my class loader class.
    java.lang.ClassFormatError: JavaNotis/SendMeldingDialog$1 (Illegal
    variable name " val$indeks")
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:431)
    at JavaNotis.Oppstart.findClass(Oppstart.java:193)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
    at JavaNotis.SendMeldingDialog.init(SendMeldingDialog.java:78)
    at JavaNotis.SendMeldingDialog.<init>(SendMeldingDialog.java:54)
    at JavaNotis.Notistavle.sendMelding(Notistavle.java:542)
    at JavaNotis.Notistavle.access$900(Notistavle.java:59)
    at JavaNotis.Notistavle$27.actionPerformed(Notistavle.java:427)
    JavaNotis/SendMeldingDialog$1 is a local class in the method
    JavaNotis.SendMeldingDialog.init, and it's accessing a final local
    variable named indeks. The compiler automatically turns this into a
    variable in the inner class called val$indeks. But look at the error
    message, there is an extra space in front of the variable name.
    This error doesn't occur when I don't use my custom class loader and
    instead load the classes through the default class loader in the JVM.
    Here is my class loading code. Is there something wrong with it?
    Again some Norwegian words, but it should still be understandable I hope.
         protected Class findClass(String name) throws ClassNotFoundException
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         private byte[] loadClassData(String name) throws ClassNotFoundException
             ByteArrayOutputStream ut = null;
             InputStream inn = null;
             try
                 JarEntry klasse = arkiv.getJarEntry(name.replace('.', '/')
    + ".class");
                 if (klasse == null)
                    throw new ClassNotFoundException("Finner ikke klassen "
    + NOTISKLASSE);
                 inn = arkiv.getInputStream(klasse);
                 ut = new ByteArrayOutputStream(inn.available());
                 byte[] kode = new byte[4096];
                 int antall = inn.read(kode);
                 while (antall > 0)
                     ut.write(kode, 0, antall);
                     antall = inn.read(kode);
                 return ut.toByteArray();
             catch (IOException ioe)
                 throw new RuntimeException(ioe.getMessage());
             finally
                 try
                    if (inn != null)
                       inn.close();
                    if (ut != null)
                       ut.close();
                 catch (IOException ioe)
         }I hope somebody can help. :-)
    Regards,
    Knut St�re

    I'm not quite sure how Java handles local classes defined within a method, but from this example it seems as if the local class isn't loaded until it is actually needed, that is when the method is called, which seems like a good thing to me.
    The parent class is already loaded as you can see. It is the loading of the inner class that fails.
    But maybe there is something I've forgotten in my loading code? I know in the "early days" you had to do a lot more to load a class, but I think all that is taken care of by the superclass of my classloader now. All I have to do is provide the raw data of the class. Isn't it so?

  • Detecting when exception was thrown using custom class loader

    Hello all,
    I would like to implement the solution described here - http://stackoverflow.com/questions/75218/how-can-i-detect-when-an-exceptions-been-thrown-globally-in-java - that uses custom class loader in order to detect when an Exeption thrown somewhere in the JVM hosting my app, please note that exceptions might be thrown from 3rd party jars the app is using. So, thanks to help I got from another post, I've managed to code the custom class loader. My question is how can the class loader wrap the original exception, as the methods in ClassLoader deals with classes, not instances. So where should I set the original exception?
    Thanks!
    Edited by: user9355666 on Sep 28, 2010 10:48 PM

    user9355666 wrote:
    I think I'm missing something fundumental, forgive me for being slow...
    This is what I did so far. For the exception wrapper I made a simple class extens Exception that recieve Exception in its ctor and store it. I also subclassed ClassLoader and override its loadClass(). I've registered it as the system classloader. My thinking was to check in that point that if the requested class is instance of Exception and if yes, returning my wrapper class wrapping this exception. But, since loadClass() return class, how can I set in the wrapper the original exception?
    In addition, let's say 2 different places in the code throws NPE, to my understanding the classloader will load NPE only once, so how throwing the NPE in the second time can be detected?you are missing a key point. you should creating a custom implementation of the NPE class which hooks into your detection code in its constructor. from that point forward, anytime any NPE (which is your custom class) is constructed, you can detect it.

  • Listening to event within custom class

    I've created a custom class that posts to a web page to authorize a user. How can I listen for an event within the custom class?
    This is my code within my main class.
    var customClass:CustomClass = new CustomClass();
    var testingString = customClass.authorize("[email protected]", "password");
    the fuction "authorize" within the customClass looks like this:
    public function authorize(user:String, password:String):void
      jSession = new URLVariables();
                                  j_Loader = new URLLoader();
                                  jSession.j_username = user;
                                  jSession.j_password = password;
                                  jSend.method = URLRequestMethod.POST;
                                  jSend.data = jSession
                                  j_Loader.load(jSend)
    How can I fire an event within my main class once the j_Loader triggers Event.COMPLETE?

    You can fire an event using the dispatchEvent() function.
    In your main class you assign a listener for the event the CustomClass dispatches after it exists.

  • How can I put Service charge to receive money from customer in Sales Return

    My company will receive the Restocking fee from customer when customer want to return the goods.
    I create a Sales Return Document for sales return but I can't put the service charge to charge my customer in the sales return document.
    If there is any possibile way to create billing document for return and AR in one billing document.

    I can't put the service charge to charge my customer in the sales return document.
    Why not ??  If you dont want to show the service charge in return sale order but to show only in credit memo, this can be achieved.  Assign routine 24 in your pricing procedure against this service charge condition type.
    G. Lakshmipathi

  • Creating event dispatching in custom class

    I have been trying to create an event dispatcher in a custom
    data transfer object class. It's a simple class and I don't know
    how to make it dispatch an event. I tried extending the
    EventDispatcher class but that doesn't appear to work either. Any
    help would be greatly appreciated.

    I have attached the code for the application and the custom
    class. This should work from what I have read, but I can not get
    the application to catch the event.
    APPLICATION
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="initThis()" layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    private var _tester:TestClass = new TestClass();
    private function initThis():void{
    addEventListener(TestClass.TEST_ACTION, onTestHandler);
    private function onTestHandler(event:Event):void{
    Alert.show("Event Dispatched");
    ]]>
    </mx:Script>
    <mx:Button x="312" y="150" label="Button"
    click="{_tester.testEvents()}"/>
    </mx:Application>
    CLASS
    package
    import flash.events.EventDispatcher;
    import flash.events.Event;
    public class TestClass extends EventDispatcher
    public static const TEST_ACTION:String = "test";
    public function testEvents():void{
    dispatchEvent(new Event(TestClass.TEST_ACTION));
    }

  • Handling Custom JavaScript Events from HtmlLoader Class

    Hey guys, just a quick question, Is it possible to handle custom javascript events just the way standard events like locationchange and DOMInitialized are handled. Say for example a HTML5 slide application that dispatches custom events when the user moves from one slide to another. I know there is an option to use ExternalInterface to talk to AS3 but for this project of mine, this is not an oiption as this HTML5 Presentation doesnt have any swf content to bridge with.
    Its just a thought since the HTMLloader has access to the javascript window object(or am i wrong). Would it be possible to access a custom function as a prototyped property of the window Object.
    Any form of tip/clarification will be appreciated.
    thanks!

    Use the HTMLHost class. You create a subclass of HTMLHost and override certain methods that are called in response to certain JavaScript behaviors. Then you assign an instance of your HTMLHost to the HTMLLoader's htmlHost property. (Since you're using the Flex HTML component, you would assign your HTMLHost subclass instance to the HTML control's htmlHost property.)

  • Custom events for custom classes

    So what I'm trying to build is a custom class wich connects
    to a php socket server using an XML socket.
    I don't know how I can broadcast an event so I can write
    something like the code below. Anyone can help ?

    To be more specific my class looks something like this
    :

  • Can I dinamicly load a class with custom class loader ?

    Can I dinamicly load a class with custom class loader ?

    Hi,
    I was wondering if you found answer to your question, and also were you using your custom class loader inside a signed applet as I am in a similar situation, and was wondering if you could help me. An example would be great...
    Thanks a lot.
    Regards.

  • How do I resolve a ClassNotFoundException for a custom class

    I am new to Java and am having frustrating problems. I am creating a Desktop application and want the application to have the capability to read from the file system.
    I created a custom class to hold mapping data and stored the object to file using ObjectOutputStream writeObject. I read it back into the program to make sure it worked. All was well and fine. I am trying to mimic the C capability to read and write entire data structures at a time. I ensured that the class (and all classes that it relied on) were serializable.
    Now back to the Desktop app. I am trying to read the object into that same custom class in my program. The program compiles fine. I have set my classpath up in Netbeans 6.1 to look to the other apps classes, have imported the classes. Again no problem.
    I also set my classpath (in the run section) to look at the jar file in the other section that contains my class. I have tried setting this runtime classpath many ways. I will get a ClassNotFoundException: MyClass at URLClassLoader ... on and on.
    I really am trying to do something simple here by just reading in a structure (class in Java). I was told previously that it is a classpath problem. How can I resolve this? I don't think that I should have to write a binary or text file that contains all of the various parameters (easier to do in one hop using
    MyClass c = (MyClass) in.readObject();
    Help is appreciated. Jay A

    jaya wrote:
    I am new to Java and am having frustrating problems. I am creating a Desktop application and want the application to have the capability to read from the file system.Very good.
    I created a custom class to hold mapping data and stored the object to file using ObjectOutputStream writeObject. I read it back into the program to make sure it worked. All was well and fine. I am trying to mimic the C capability to read and write entire data structures at a time. I ensured that the class (and all classes that it relied on) were serializable.I'm not sure why you think Object streams are the way to go here. Why aren't a text representation and a toString call good enough? Sounds like you just want a simple persistence mechanism without a relational database. Writing a Map of <key, value> pairs using a PrintWriter would seem enough to me and parsing each pair on a line to read it back in would seem sufficient to me.
    Now back to the Desktop app. I am trying to read the object into that same custom class in my program. Why? What are you trying to do? Why can't your Desktop app instantiate an instance of the custom class and be done with it?
    The program compiles fine. I have set my classpath up in Netbeans 6.1 to look to the other apps classes, have imported the classes. Again no problem.So does your NetBeans classpath include your custom class?
    I also set my classpath (in the run section) to look at the jar file in the other section that contains my class. Why do you have to package the other class in a JAR? Why can't that package just be part of your current project? Or are they separate projects, and you want to treat the first one like a 3rd party JAR?
    I have tried setting this runtime classpath many ways. I will get a ClassNotFoundException: MyClass at URLClassLoader ... on and on.You aren't setting CLASSPATH correctly. You don't need a URL class loader. You're making this far too complicated. It's a much easier thing than this.
    I really am trying to do something simple here by just reading in a structure (class in Java). I was told previously that it is a classpath problem. How can I resolve this? I don't think that I should have to write a binary or text file that contains all of the various parameters (easier to do in one hop using
    MyClass c = (MyClass) in.readObject();This is not the way to do it.
    CNF exception means one thing: a .class that you need to load isn't in the CLASSPATH. That advice you got is correct. You need to figure out how to make it so.
    Your description is confusing.
    I think your mistake is assuming that serialization is the best way to persist that mapping data. Without knowing more about the details, I think adding two method to the "custom class" that encapsulated the mapping data should be sufficient. Create a static read() method that takes a java.io.Reader and returns a populated instance of your class. Create a static write() method that accepts a java.io.Writer and an instance of your class and returns void. Have them read and write plain text. Then either make that source code part of your NetBeans project or package it into a JAR and put that in your CLASSPATH. Either way, if you don't do it properly you'll get that CNF exception. Keep plugging until you get it right.
    %

  • Unit testing: Mocking custom classes with null

    Hi,
    I was trying to save time on testing the usual hashCode() and equals() methods so I got this class: http://www.cornetdesign.com/files/BeanTestCase.java.txt
    I altered it a bit as it wasn't handling standard classes only primitives.
    Anyway, I got to the point to include my own custom classes.
    I have to create a 'mock' object for my class properties, e.g. field.getType().newInstance()
    Fine, but there are some tricky instances. E.g. when I'd like to create an instance of java.net.URL which takes a URL as String in the constructor.
    This is almost impossible to automate as it has to be a valid URL format not just a random String.
    So, I thought I set them to null, e.g.
    assertTrue(o1.equals(o2))
    as both properties are null.
    Is this the right approach you think?
    I welcome any suggestions.
    My initial idea was to save enormous amount of time automating the hashCode() and equals() method tests as they took so long to write.
    Thanks

    Trouble would be that you are only testing the null branch of the equals or hashCode, which typically have to check for null, then if not null do an actual comparison.
    It's worth the effort of learning to use a package such as EasyMock to create and program mock objects. It's tidiier if you are progamming to interfaces, however, but it will mock ordinary objects, though probably not if they are final.
    What you could do is to define a factory interface, and have a table of anonymous classes wich generate various types. In effect create a library of dumy object factories.
    Something like:
    private interface DummyGenerator {
          Object generate(int idx);
          Class<?> getType();
    private final static DummyGenerator[] generatorsTable {
        new DummyGenerator() {
               public Object generate(int idx) {
                 return new URL("http://nowhere.com/" + idx);
         public Class<?> getType() { return URL.class; }
    .. generators for other classes
    private final static Map<Class<?>, DummyGenerator> genMap = new HashMap<Class<?>, DummyGenerator>(generatiorsTable.length);
    static {
        for(DummyGenerator gen : generatorsTable)
            genMap.put(gen.getType(), gen);
    }

  • Add button to a datagrid with custom class

    Hi.
    I have a custom class that i put in the dataprovider to a datagrid. And when i column with buttons i get the following error.
    ReferenceError: Error #1069: Property null not found on COMPONENTS.Output.OutputFile and there is no default value.
    at mx.controls::Button/set data()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\controls\Button.as:873]
    at mx.controls::DataGrid/http://www.adobe.com/2006/flex/mx/internal::setupRendererFromData()[E:\dev\3.0.x\framework s\projects\framework\src\mx\controls\DataGrid.as:1646]
    at mx.controls::DataGrid/commitProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\m x\controls\DataGrid.as:1606]
    at mx.core::UIComponent/validateProperties()[E:\dev\3.0.x\frameworks\projects\framework\src\ mx\core\UIComponent.as:5670]
    at mx.managers::LayoutManager/validateProperties()[E:\dev\3.0.x\frameworks\projects\framewor k\src\mx\managers\LayoutManager.as:519]
    at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\3.0.x\frameworks\projects\frame work\src\mx\managers\LayoutManager.as:669]
    at Function/http://adobe.com/AS3/2006/builtin::apply()
    at mx.core::UIComponent/callLaterDispatcher2()[E:\dev\3.0.x\frameworks\projects\framework\sr c\mx\core\UIComponent.as:8460]
    at mx.core::UIComponent/callLaterDispatcher()[E:\dev\3.0.x\frameworks\projects\framework\src \mx\core\UIComponent.as:8403]
    What shuld i do?
    Thanks for help.

    If you are talking SE54 and Maintenance Views, when I do an SM30 on the Maintenance View and do SYSTEM->STATUS, I see GUI STATUS ZULG on program SAPLSVIM.  If you look at that status, I see two buttons with dynamic text.  The first one is call GPRF and has dynamic text VIM_PR_STAT_TXT_CH.  You can find a suitable PBO event to set the text of that function code and if that works, find a suitable PAI event to respond to that function.
    I recall finding some documentation on customizing the GUI STATUS but no luck today trying to find it.
    Let us know how it goes.

  • Capture Customer Class in time of BP creation from Screen

    Hi All,
    I am facing a problem that I need to capture  Customer Class , Sales Area Template and ID type in time of BP creation in DCHCK event. I have to check if user is putting these value correctly or not. If user entered wrong value then I have to through error message and not to save to BP.
    Foe example I am using 'BUP_BUPA_BUT000_GET' to get all other data along with BP type and so on.
    Plesae help regarding this if any one is aware of it.
    Thanks & Regards
    Ajoy

    Hi,
    asaha... I want to know how it would be done ?
    by ABAP customization or in the CRM IMG itself ?
    can you brief about it ..
    Thanks
    " RA "

  • Sqlite, moving sqlstatements to a custom class

    I'm working on a FB AIR app.
    I have a main.mxml file with a source to a main.as file.
    My main.as file is getting very bloated with sqlstatements. I want to move these to a custom class, but I don't know how to proceed.
    I found an example of a package on this page: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/data/SQLConnectio n.html#begin()
    about a 3rd of the way down.
    The example above is exactly what I want to do, but I don't know how to adapt this for use in my main.as file beyond importing the class and instantiating it. How do I assign my values to the class file? How do I use the class to load up the dataProvider, etc...
    Also, in the example above the class extends Sprite. This sounds like it's meant for a Flash application. Would I still extend Sprite in Flex 4? I have done a couple of simple events, passing data back to the main app with the Flash.Events.Event, so the use of Sprite causes some confusion.
    In a previous post, Amy suggested using Robotlegs. I think I need to get a handle on using Flex before I explore other architectures. I'm just not that sophisticated yet.
    Thanks
    Kristin

    ok, a quick example
    make a new package called utilities and then a new actionscript class called DatabaseManager
    package utilities
         import flash.data.SQLConnection;
         import flash.data.SQLResult;
         import flash.data.SQLStatement;
         import flash.filesystem.File;
         import mx.collections.ArrayCollection;
         public class DatabaseManager
              private var sqlConnection:SQLConnection;
              private var stm:SQLStatement;
              public function DatabaseManager()
                   //connect to database
                   sqlConnection = new SQLConnection();
                   sqlConnection.open(File.applicationStorageDirectory.resolvePath("whatever"));
                   //create tables if not exist
                   stm = new SQLStatement();
                   stm.sqlConnection = sqlConnection;
                   stm.text = "create your table here";
                   stm.execute();
                   //create more tables
              public function getThings():ArrayCollection
                   stm = new SQLStatement();
                   stm.sqlConnection = sqlConnection;
                   stm.text = "your query";
              public function addStuff(stuff:Object):int
    then in your main file you need to import
    import utilities.DatabaseManager;
    instantiate the class, this connects and creates tables
    private var myDB:DatabaseManager = new DatabaseManager();
    then to use it
    var listFromDatabase:ArrayCollection = myDB.getThings();
    insertid = myDB.addStuff(thingToAdd);
    hope that gives you an idea 

Maybe you are looking for

  • Error when creating Advanced Table in Advanced Table

    Hello, I have created an advanced table, which works fine. When I add an inner advanced table to the outer advanced table I receive the following error stack (see below) and I have no idea what is causing this error. I have only added 1 column to the

  • How to copy a file from Java code

    I have written a file through Java code in folder, say, "A". Now, I want a copy of that file exactly the same in some other folder "B". How, it can be done?

  • Multiple Browser Based Review Crashing - Acrobat 8.1.2 / Acrobat 9.0.0

    In Acrobat Professional v8.1.2 and v9.0.0, if two browser-based review windows are open and the Comments & Markup toolbar is embedded in both windows, when a comment is applied in one of the windows the Send/Receive button flickers and Acrobat crashe

  • Pickup and process zip file in watch folder

    Hi, Could someone refer me to an example where it shows me how to use Java script in the Execute Script service to do the following: - Pickup the zip file from the Watch Folder - Unzip the zip file - Loop through all the folders, look for the documen

  • Sales Order-Line Item Number Field not Appearing

    Dear All I have an issue in which, in sales order, the field where I enter material, I am not able to see the line item number. For example; if the Material X is entered, I cannot see the item number as 10. Can I know what might be the problem. Thank