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

MyClassmyClass = newmyClass(context);

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

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

publicclassMyClass {

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

    privateMyClass() {
    }

    publicstatic CustomListner getInstance() {
        return singletonMyClass;
    }

    publicinterfaceCustomListener {
        publicvoiddoThisWhenTriggered();
    }

    publicvoidsetOnCustomListener(CustomListenerListener listener) {
        this.listeners.add(listener);
    }

    publicvoidgenerateTrigger() {
        CustomListener listener = listeners.get(0);

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

}

from MyActivity.java you can call

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

and similarly in MyBroadcastReceiver.java

publicvoidcallMyClass(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"