Please forgive the very basic nature of this questions - but we all have to start somewhere. I've done some googling but all answers seem to relate to UI Events.
I am creating a very simple android app that will display your location on screen. I have my main class (HelloAndroid at the moment) that extends Activity and I have created a class LcoationUpdateHandler that listens for updates.
HelloAndroid holds an instance of LocationUpdateHandler so my question is how does the LocationUpdateHandler communicate with HelloAndroid.
In flex I would dispatch an event from one to the other but from the searching I have done this doesn't seem like a very java-y way of doing things?
Thanks for your help.
When your HelloAndroid instance creates an instance of LocationUpdateHandler it can pass a reference to itself in the constructor, which LocationUpdateHandler can store to use for future method calls in the case of events.
For these kinds of situations you don't really need to know what type of object instatiated LocationUpdateHandler. This is were interfaces come in, you can define an interface defining the event methods and implement that interface so that LocationUpdateHandler can keep a reference to that interface to deliver events.
If the situation is symmetrical, both classes can implement the same event interface.
It sounds like what you're looking for is the Observer pattern. The way it works is that observers register with the object that they are observing, such that they can be notified on events.
In your specific case, if you want LocationUpdateHandler to push information to HelloAndroid, it has to know about HelloAndroid. So your LocationUpdateHandler should at least contain a reference to HelloAndroid, but to generalize this, it should have a List of observers that all implement a common interface containing a callback function that would be called whenever LocationUpdateHandler has an update.
Related
While consulting the javadocs for GwtEvent class this text snippet got me confused:
There is no need for an application's custom event types to extend
GwtEvent. Prefer Event instead.
Can someone please give a concrete situation example where Event is preferred to the gwtevent class?
Should ClearEvent ( defined here : http://alextretyakov.blogspot.ro/2011/11/gwt-event-bus-basics.html ) extend GwtEvent class or should it directly extend Event class?
GwtEvent extends Event. It just seems that the GWT team need some functionalities for most of its events. But you probably don't need those.
In our application most events are consumed directly. So we don't need to have those isLive(), kill(), revive() methods. I guess it's the same for most people.
IMO such methods are required when a chain of listeners can catch the event and forward it to each other. You would want to mark the event as "processed" to avoid it being consumed when the processing is over.
The code in the post you provided is not using those methods. So the answer is: the author didn't need to extends GWTEvent. Event will work just fine.
I have a GUI class with a menu of buttons and textfields. Depending on what choices that is made in the menu and the input, methods in the GUI class are calling methods in the Logic class to send the input and create new objects of Customer class and Account class and so on.
To be able to communicate between the GUI- and the Logic class, I first create an object of the Logic class and I do that inside the GUI class, since it's here I have my main method. It this the best way to do it? Do I need some kind of reference variable between GUI- and Logic class or just use the reference when the object was created in the beginning of the GUI class? I guess to be able to communicate with a class, it must be an object first!? Thanks!
Logic logic = new Logic();
logic.addCustomer(name, number);
Ideally you shouldn't directly create the logic class.
You should break down the functionality into a number of small classes, each of which satisfy a responsibility.
A simplistic way would be for the GUI class to create listeners which listen to the user events. In response the to the use event they fire events that your logic registers itself for. Then when the event is received the logic class can perform the functionality.
You should read about observer pattern, event driven design...
You can read about event driven programming here http://en.wikipedia.org/wiki/Event-driven_programming .
I would instantiate the Logic class outside the GUI, but pass it as an argument to the GUI constructor. It's nearly equivalent to what you are already doing, but I think it makes it clearer that the GUI uses a Logic object. Also, it's possible that Logic does some other things before/after the GUI starts/closes; it might not be the case now, but it could be true in the future if you extend your program.
Many other answers tell you to look at MVC, but that might be overkill for your project. It can decrease complexity for a large project, but increase it for a small one.
EDIT:
Logic login = new Logic();
...
MyGUI gui = new MyGUI(logic);
...
I would suggest you do some researches on the MVC architecture. Your GUI (view) shouldn't interact directly with your model (logic). Implement a controller that will get the "signals" from your view and will be in charge to create your "logic objects" and work with them.
You can create on object of type Logic in your main and store a reference of the object in your Window object - so you can access your Logic object as long as the window exists.
You should look up the Singleton design pattern for such trivial scenarios.
By default, Java uses Reference variables. Hence, if you instantiate your object in GUI class, make sure you send the object via method calls to your processing class.
Alternatively, you can look into singleton classes, which will return only one instance of the class. Inside that class, instantiate all the objects that you will need globally, and re-use that instance throughout your program.
Generally you can. If your application is very simple.
But this approach is not scalable. As your application gets more complex it became much harder for development and support. Try to consider Model–view–controller pattern to define a best way for your design. (according to your nick name I'll take a risk to propose an alternative link)
I'm building an Android app and a Blackberry app (same app different platforms). There is an abstract class that I am building that will handle events. For instance, I touch the "save" button on Android it posts a notif/event. The abstract class receives that event. I press the "save" button on Blackberry, it does the same thing.
What is the best way to accomplish this? I've looked at EventObject, as well as MBeans and its notification classes but they appear overly complicated. In objective-c I simply register a class instance for notifications with the objective-c notificationcenter, and then in the class that triggers the notif, at the time of trigger we do something along the lines of "postNotification". Is there anything that easy in Java? Also I need to send Objects with those notifications.
Oh at I suppose we actually can't use any MBeans classes. Not part of Blackberry Java version.
Thanks!
With BlackBerry, if you're planning on these events to be generated from UI elements (ButtonField, ListField, etc) they all come with Field.setChangeListener(FieldChangeListener) so you just have to attach a listener to that. If you want this to be something that responds to things like IO or processing, you could use the Event and EventListener classes to accomplish this. Personally I think they're a little more than what I need for simple notifications, so I generally make my own simple interfaces.
Say you have a class that extends Thread that connects to a web service to download an XML file that lists states and their capitals. and processes it. You could create an interface EventGenerator with abstract methods public void addEventHandler(EventHandler) and protected void notifyHandlers(Object obj). Inside of this you have a Vector that stores EventHandlers that your notifyHandlers() can loop through and send a call to handler.handleEvent(Object). When you are finished with processing the data, you wrap it up in an Oject (maybe Hashtable, or a custom States bean), we'll call it states, and internally call notifyHandlers(states). Now as you go through each EventHandler, you call handler.handleEvent(states). You may consider putting a try/catch around each call to it so one EventHandler doesn't prevent all of them from running.
So onto the EventHandlers. This is another interface that has the abstract method public void handleEvent(Object obj). Say you have a Screen that, after the states are retrieved, will display them in a list. This Screen will implement EventHandler and then register itself with the EventGenerator using generator.addEventHandler(this). Whenever the processing is done, this method will get called and you can do whatever you want with the Object that is returned.
An addition you can implement is changing public void handleEvent(Object obj) to public boolean handleEvent(Object obj) and, similarly to navigation methods in BB, return true if the event was handled and nothing else should try processing it.
I need to pass an object from one class to many different classes.
The aim of this is to create one method that broadcasts the object to any other classes that are listening. This is so that more classes can be added and I just need to implement a listener function for that class and not edit any of the framework.
I am trying to accomplish this without the use of JMS (if it's possible!)
Observer pattern to the rescue! Woooosh!
Let your Subject define a method for relaying that object to many listening Observers. You can then dynamically add and remove listeners.
I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model's state).
Is there something in Java similar to Cocoa's NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects "fire off" a notification?
Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don't worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it "ScanListener", like
public interface ScanListener
{
public void scanStarted();
public void scanCompleted();
}
Now the Loader defines a method for your other code to register for callbacks, like
public void addScanListener(ScanListener listener)
{
listeners.add(listener);
}
The Loader, when it starts a scan, executes the following code
for (ScanListener listener : listeners)
{
listener.scanStarted();
}
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls "loader.addScanListener(this)". Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It's all up to you.
What sort of notifications are you looking for? If all you want is for one object to be able to tell anybody else "hey, I've changed, update accordingly", the easiest way is to use the existing Observer interface and Observable class. Or write your own with an interface that defines what you want to get called on the listeners from the one that's changed.
There's no pre-existing per-process service that dispatches events in java that's equivalent to the default NSNotificationCenter. In java, the type of the event is specified by the event object being a particular type (which also means that the notification method depends on that type) rather than using a string. Prior to generics, writing a general event dispatcher and receiver that is also typesafe isn't really possible (witness the proliferation of *Event classes and *EventListener interfaces in the AWT and Spring libraries).
There are some facilities for event dispatch. As Paul mentioned, there's java.util.Observable, which as you point out, requires subclassing. There's also java.beans.PropertyChangeSupport, which could be useful depending on your situation.
You could also write one yourself. The source for PropertyChangeSupport is likely available in the openjdk, and you could look at the abandoned Apache Commons Event project. Depending on your needs, you may have to worry about stuff like threading, seralization, memory leaks (ensuring deregistration or using weak references), and concurrent modification (iterate over a copy of your list of listeners, as a listener may decide to unregister itself in response to a change).
Now that generics exist in Java, a generic event dispatch library would be possible; however, I haven't come across any. Anyone?
There's actually a facility built in to Java that does exactly what you want, but it's not something you may have considered, and, to be honest, it is likely a bit heavyweight for what you want.
That said, however, it does exist.
It's JMX.
You create MBeans, and then others can register for events from those MBeans. The MBean can then send of a Notification.
I personally wouldn't consider using it for this case (I'd just pound out my own), but the facility is there and it well defined and documented.
Not Java, but the IPython project has a notification center written in Python here that you could use as a template for a Java version.
In Java this would be a provider firing notifications to its listeners. But Java does not offer the loose coupling you get with Cocoa's NSNotification because in Java providers and subscribers must have references to each other. Compare for this chapter 18 in "Learn Objective-C for Java Developers".
There is an implementation of IOS NSNotificationCenter in Java.
You can find sources code in :
This Github project