1

I've the following 3 classes,please have a look:

Main.java:

package com.tsc.sendit.worker;

public class Main {

    public static void main(String[] args) {
        new Thread(new Loader()).start();
    }
}

Loader.java

package com.tsc.sendit.worker;

import java.io.File;

public class Loader implements Runnable,Divider.OnExceptionChangeListener {

    private Divider divider;

    public Loader(){
        divider = Divider.getInstance();
        // register listener
        divider.setOnExceptionChangeListener(this);
    }

    @Override
    public void run() {
        // a random fileName (it doesn't exist)
        divider.setFile(new File("f:\\licenses.txt"));
    }

    @Override
    public void onExceptionChanged(String errorMsg) {
        System.out.println(errorMsg);
    }
}

Divider.java

package com.tsc.sendit.worker;

import java.io.File;
import java.io.FileNotFoundException;

public class Divider {

    private static Divider divider;

    private String errorMsg;
    private OnExceptionChangeListener onExceptionChangeListener;

    private Divider() {}

    public static Divider getInstance() {
        if(divider==null)
            divider = new Divider();
        return divider;
    }

    public void setOnExceptionChangeListener(OnExceptionChangeListener onExceptionChangeListener) {
        this.onExceptionChangeListener = onExceptionChangeListener;
        if(errorMsg!=null) {
            notifyListener();
        }
    }

    private void notifyListener() {
        onExceptionChangeListener.onExceptionChanged(errorMsg);
    }

    public void setFile(File file) {
        startDividing();
    }

    private void startDividing() {
        try {
            throw new FileNotFoundException();
        } catch (FileNotFoundException e) {
            errorMsg = "abc";
        }
    }

    interface OnExceptionChangeListener {
        void onExceptionChanged(String errorMsg);
    }
}

I've even debugged this code which led me to the conclusion that though errorMsg changes, the custom listener ain't working. I followed the method mentioned here:how-to-create-custom-listeners-in-java

(though the code there works)

Please provide me with a solution. Thanks in advance.

  • the call to `notifyListener` is done only when `setOnExceptionChangeListener` is called, not when `errorMsg`is set – jhamon Jun 23 '20 at 14:04

1 Answers1

4

There's nothing magic about the name 'event listener'. You need to actually fire them when you set errorMsg, there is no way to tell java: Can you just sort of make this work automagically?

So, immediately after the line errorMsg = "abc", you probably need notifyListener();, and your notifyListener implementation needs a null guard:

if (onExceptionChangeListener != null) onExceptionChangeListener.onExceptionChanged(errorMsg);

or better yet, make a method updateErrorMsg(String msg), which both updates errorMsg and notifies the listener if it isn't null.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72