Android - event listener

android, android-activity, class, events, listener

Solution

If "I implement some class" means that you have declared a nested class inside your Activity class than nested non-static class will have a reference to parent class object.

In general, you can always create dispatcher/listener pattern your self. Create listener interface and add either addListener or setListener method to class that will dispatch event.

Example of listener:

public interface IAsyncFetchListener extends EventListener {
    void onComplete(String item);
    void onError(Throwable error);
}

Example of event dispatcher:

public class FileDownloader {
    IAsyncFetchListener fetchListener = null;
    ...
    private void doInBackground(URL url) {
        ...
        if (this.fetchListener != null)
            this.fetchListener.onComplete(result);
    }

    public void setListener(IAsyncFetchListener listener) {
        this.fetchListener = listener
    }
}

Example of class with event listener:

public class MyClass {

    public void doSomething() {
        FileDownloader downloader = new FileDownloader();

        downloader.setListener(new IAsyncFetchListener() {

            public void onComplete(String item) {
                // do something with item
            }

            public void onError(Throwable error) {
                // report error
            }
        });

        downloader.start();
    }
}

Problem

I hope this will be simple question. I have main activity, on this activity I create an instance of some class. How to send some event form one class to main one? How to setup some kind a listener to send notifications between classes. Only option what I know/use right now is to keep reference to parent class and call directly some function from child class. I'm wonder if it possible to create something like is in ActionScript, where I can call to dispatchEvent(new Event("name")) and later setup addEventlistener("name" function) ??

Original source