Skip to content Skip to sidebar Skip to footer

MyActivity Implements Custom Listener From MyClass.java But Listener Is Always NULL

MyActivity implements a CustomListener defined in MyClass.java. I have a function defined in MyClass that should trigger the listener and do some action(finish() MyActivity) define

Solution 1:

You never instantiate listener (declared as CustomListener listener;) and therefore its always null, you just need to set the activity as the listener, as it implements the interface:

myClass.setOnCustomListener(this);

As seen in your code, you create a new instance of the class in the receiver, so the listener you set does not exist in the listeners list of new instance, since the list is not static.


Solution 2:

Its because

 MyClass myClass = new myClass(context);

in MyBroadcastReceiver.java. This will create a new instance.

So I think it will be better to use MyClass.java as Singleton.

public class MyClass {

    private Contect ctx;
    ArrayList<CustomListener> listeners = new ArrayList<CustomListener>();
    private static final MyClass singletonMyClass = new MyClass();

    private MyClass() {
    }

    public static CustomListner getInstance() {
        return singletonMyClass;
    }

    public interface CustomListener {
        public void doThisWhenTriggered();
    }

    public void setOnCustomListener(CustomListenerListener listener) {
        this.listeners.add(listener);
    }

    public void generateTrigger() {
        CustomListener listener = listeners.get(0);

        if (listener != null)
            listener.doThisWhenTriggered();
        else
            Log.d("MyAPP", "Listener is NULL");
    }

}

from MyActivity.java you can call

MyClass myClass = MyClass.getInstance();
myClass.setOnCustomListener(listener);

and similarly in MyBroadcastReceiver.java

public void callMyClass(Context context)
{

    MyClass myClass= MyClass.getInstance();
    myClass.generateTrigger();

}

Hope this helps!!!.


Post a Comment for "MyActivity Implements Custom Listener From MyClass.java But Listener Is Always NULL"