I looked for this online, but couldn't find an adequate explanation to what it exactly does. What I saw was a Java Interface and it was passed as a parameter in another class as a "Listener". People added various listeners to a list and called them all through a single method.
I'm not sure why I would use it. Can someone care to explain?
This is my original help post where someone told me to use listeners.
Link
In the code example that you linked the KillMonsterEventListener
public interface KillMonsterEventListener {
void onKillMonster ();
}
provides a way for users of your API to tell you something like this:
Here is a piece of code. When a monster is killed, call it back. I will decide what to do.
This is a way for me to plug in my code at a specific point in your execution stream (specifically, at the point when a monster is killed). I can do something like this:
yourClass.addKillMonsterEventListener(
new KillMonsterEventListener() {
public onKillMonster() {
System.out.println("A good monster is a dead monster!");
}
}
);
Somewhere else I could add another listener:
yourClass.addKillMonsterEventListener(
new KillMonsterEventListener() {
public onKillMonster() {
monsterCount--;
}
}
);
When your code goes through the list of listeners on killing a monster, i.e.
for (KillMonsterEventListener listener : listeners) {
listener.onKillMonster()
}
both my code snippets (i.e. the monsterCount-- and the printout) get executed. The nice thing about it is that your code is completely decoupled from mine: it has no idea what I am printing, what variable I am decrementing, and so on.
Listener is a common form of implementing the observer design patter in Java. This technique is also referred to as the callback, which is a term coming from the world of procedural languages.
Observers register themselves by the observable, which in turn calls back the observers whenever some event occurs or when they should be notified about something.
Many framework libraries play the role of the observable, e.g.:
You register yourself (i.e., your implementation of the listener interface) as a listener of incoming messages in a messaging middleware.
You register yourself as a listener of some changes made by the user in the operating system.
You register yourself as a listener of GUI events, such as a button was click on.
Example in Java code:
Part 1 - The observable entity
import java.util.LinkedList;
import java.util.List;
public class Observable {
private List<Observer> observers;
public Observable() {
observers = new LinkedList<>();
}
public void addObsever(Observer observer) {
observers.add(observer);
}
private void notifyObservers(String whatHappened) {
for (Observer observer : observers) {
observer.onSomethingHappened(whatHappened);
}
}
public void doSomeStuff() {
// ...
// Do some business logic here.
// ...
// Now we want to notify all the listeners about something.
notifyObservers("We found it!");
// ...
// Do some business logic here
// ...
}
}
Part 2 - The observer/listener interface
public interface Observer {
void onSomethingHappened(String whatHappened);
}
Part 3 - Basic implementation of the observer/listener interface
public class MyObserver implements Observer {
#Override
public void onSomethingHappened(String whatHappened) {
System.out.println(whatHappened);
}
}
Part 4 - Putting it all together
public class Main {
public static void main(String[] args) {
// Create the observable.
Observable myObservable = new Observable();
// Create the observers (aka listeners).
Observer myObserverA = new MyObserver();
Observer myObserverB = new MyObserver();
// Register the observers (aka listeners).
myObservable.addObsever(myObserverA);
myObservable.addObsever(myObserverB);
myObservable.doSomeStuff();
}
}
And the result on standard output will be:
We found it!
We found it!
This is part of a programming paradigm called event-driven programming. Objects send messages to other objects on certain occasions, for example when they change. This is used often in GUI programming. Each GUI widget is implemented by a class. When you want to handle e.g. mouse clicks from the user, you add a listener (also called event handler) to GUI widget. When the user clicks on the widget, the widget sends the event to the registered listener(s) so that the application can respond to the mouse click. This seperates the framework (the GUI widget class) and the application code. (In some GUI frameworks, such as Swing, you can add an arbitrary number of listeners to an object; in others, you can specify only one.)
Also in other areas event-driven programming is useful. You might want to observe an object (see Observer pattern). For example, a collection which supports this, might send an event if its contents change. If you need to perform some processing if this occurs, you can add yourself as a listener to this class. The alternative would be to call the post-processing every time you add an item to the collection, but this error-prone.
Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example, HttpSessionListener.
Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc.
You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when lifecycle events occur.
Here is the blog post for Servlet Listener
http://array151.blogspot.in/2016/12/servlet-listener.html
Use a listener to let other code inform you of "conditions"/"events". For instance a "mouse listener" could be called if the mouse would have been moved/clicked/dragged. It depends on your application why it provides for listeners.
Listeners do some work when an event occurs. They are called as "Event Listeners".
Events like click, hover etc..
For Example, we have ActionListener interface in Java. It calls actionPerformed() method when an event occurs.
You can refer http://java.about.com/od/a/g/Actionlistener.htm for more info.
Listeners are used for notify about state changes. You can think about Listeners in most of time as Observers, so every time something interesting happen your listener will be called.
You can read more about patterns in Java on following websites:
http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial
http://www.developer.com/java/implementing-behavioral-patterns-in-java.html
tldr: I'm wondering if it's better to send a call to an activity to start a method or if it's better to loop in the activity to see if the object method has been triggered.
Description:
I'm creating a timer which is triggered by sound in android studio. I've created a separate class from my timerActivity, called percussionDetector. Using the library TarsosDSP and it's integrated functions. The question I'm having is if it's more appropriate to call the method to start the clock in the activity from the percussionDetector or if it's better to loop and check if the value becomes true in the the activity?
here's some pseudo-code to better describe my question:
//is this the best way to go? (MainActivity)
while(percussionDetector.onSetTriggered())
{
if(timer!=null){
stopTimer();
}else{
startTimer();
}
}
//or this? (Object class)
public void onSetTriggered(){
if(timer!=null){
Activity.stopTimer();
}else{
Activity.startTimer();
}
}
Thanks for the help beforehand!
I have a utility class that will be running an async task using HTTP. On complete I've setup an interface so I can just fire off methods to process the results (whether it's an activity, fragment, etc.). This way as long as I implement the interface I can always pass 'this' from wherever I am and it will call the standard onComplete() method to process results when they're available.
My issue is that in most cases I just need one HTTP call so it's straight forward. What about when I need to do 1,2,3,N HTTP calls in a fragment let's say what will happen when they all complete and go to fire the onComplete() method I set up?
Will the OS queue everything up properly since it's now the main GUI thread and I just have to keep track of a simple counter like numTasks = 0, and each time onComplete() fires just increment so I know when all tasks are done?
And also how do I know which call is completing to handle the different responses accordingly? I could get back something different from each and need to process accordingly in the same onComplete() method right? In PHP you can check who called you, is there a way to do that in Java and somehow distinguish between the different instances of the async subclass object I created? Each time I create this object I'll be storing it as a variable, it'll do it's async stuff, than the onComplete() gets fired from within it for the callback.
Fragment <--implements interface for onComplete()
-instance 1 (implements async) <--pass 'this' as callback
-instance 2 (implements async) <--pass 'this' as callback
-onComplete() <---fired from within instance 1 & instance 2 during postExecute()
-increment task counter++ to know when we're done, but how to differentiate which instance completed and called me to handle response properly?
Thanks.
The interface is just a conduit through which Java passes information. Assume that your Fragment class passes its context to your utility class:
new Async().executeHTTP(this);
In the utility class:
public class Async {
public void executeHTTP(Context context){
...
((YourInterface)context).onComplete();
}
}
Because you're using the context from your fragment instance, the onComplete() method is only called for that particular instance. The interface creates a conduit between the interface caller and the interface implementation. (In this case, Async instance->Fragment instance.)
If you want to differentiate between different calls from the same instance, just pass in an identifier and pass it back through your onComplete method.
new Async().executeHTTP(this, ++requestID);
...and in the utility class:
public class Async {
public void executeHTTP(Context context, int id){
...
((YourInterface)context).onComplete(id);
}
}
I have a java class buried deep in an SDK that performs an action and returns a boolean. It has no knowledge of the application's main activity, but I need the main activity to receive that boolean value.
I've seen a lot of questions regarding callbacks, broadcasts, and listeners but they all seem to have knowledge of the activity. My pojo does have an activityContext but I don't know how to get the value back to the application's main activity.
I'm already using an AsyncTask in my pojo and I'm trying to figure out how to send the boolean in the onPostExecute method in a way that the application's main activity can receive it.
Does anybody know how to do this?
I'd suggest using a message bus or observable/observer pattern.
Square has Otto a nice little open-source library that implements a message bus.
Observer pattern is well described at wikipedia for example.
Either way what you will have to do is essentially start listening to either your POJO if you make it Observable, or subscribe for bus events in onResume() (or onStart()) and stop listening in onPause() in your activity.
BUS
I like bus more because of it's loose coupling and the fact that you can send any arbitrary POJOs to the bus and only listen to one specific type for example.
so you post a message this:
bus.post(new SomethingICareAbout("I really really do"));
and elsewhere in your codebase (in your case in the activity):
#Subscribe
public void onSomethingIcareAbout(SomethingICareAbout thingsAndStuff) {
// TODO: React to the event somehow. Use what you received.
}
#Subscribe
public void onSomethingElseIcareAbout(SomethingElseICareAbout otherThings) {
// TODO: React to the event somehow. Use what you received.
}
The above is intentionally simplified, you still need to create the bus and subscribe to it, but you will find that in the docs :P
Also it uses annotations and is really lightweight (codewise).
Observer / Observable
Observer/Observable on the other had is part of Java, so it's built in. But it is tightly coupled, your activity will have to implement Observer, your POJO will implement Observable and you willl have to implement update() method in your Activity, this one will get all the updates no matter what you send by the Observable.
I hope this makes sense a bit :)
I want to write a class that handles all my network interaction called NetworkManager. So using an instance of this class I'd have something like:
NetworkManager nm = new NetworkManager();
...
nm.login(username, password);
...
However, what is the best approach so this network manager can do something on the UI thread once some response has been received? Modelling on a onClick style event I think this would be like:
nm.getPicture(new NetworkListener() {
#Override
public void run(Picture p){
updateUI(p);
}
Where I am unsure how to write the getPicture method and the NetworkListener() class.
I don't want to use AsyncTask, because this would mean I'd have to write the server code at different parts of the MainActivity. I have also considered a broadcaster and a listener, but this seems too much for a one off event.
Checkout Retrofit (http://square.github.io/retrofit/) it might be useful to consider for integrating the part of your network class. I'm not sure if you will have multiple similar calls, but if so, I would advice you to apply the Observer pattern, where you make the call and wait for the response asynchronously, yet, there's a nice library to accomplish that, very well documented, called Otto (http://square.github.io/otto/).