Edwin Evans
Edwin Evans

Reputation: 2836

Are there any general listeners defined in Android or Java

Sometimes I want a simple generic Listener without defining my own class. Is there a predefined "something happened and here is a string or object or whatever" in Java or Android?

Upvotes: 4

Views: 1415

Answers (3)

SharkAlley
SharkAlley

Reputation: 11659

If you want to avoid defining a listener class, consider defining callback methods directly in the observable:

abstract class MyWorker{

    public MyWorker(){
        //...    
        onComplete(); 
    }

    protected abstract void onComplete();

}

Then override them later:

new MyWorker(){

    protected void onComplete(){
        //..
    }
}

Obviously, this is not suitable for every situation. Sometimes you need a real listener class.

Upvotes: 0

Mark Peters
Mark Peters

Reputation: 81084

A project I've worked on had that. It lead to some frightfully unreadable and unmaintainable code once a class implemented the "MyListener" interface to handle two completely different kind of events. There was a lack of separation of concerns, and you had no idea when or how that method might be invoked.

public interface GenericListener {
    public void handleMyEvent(Object sourceObj, int eventCode);
}

//...later on there's some implementation
public void handleMyEvent(Object sourceObj, int eventCode) {
    if ( sourceObj == startDownloadButton && eventCode == MyButton.CLICKED ) {
        //... 20 lines of code to start download
    } else if ( sourceObj instanceOf DownloadStatus && eventCode == DownloadStatus.COMPLETE ) {
        //... 10 lines of code to display status
    } else //... and on and on...
}

This isn't the kind of code duplication you need to avoid. Just because two methods/interfaces share the same basic signature doesn't mean they should be combined into one. I suggest you create listener interfaces that are completely self-documenting with regards to when and how they are used.

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234807

There's java.util.Observer, but that only works for Observable subclasses. (That is, anything can implement the Observer interface, but it can only observe Observable objects.)

Upvotes: 2

Related Questions