Custom event listener on Android app
Solution 1:
-
Define a callback interface
public interface NewsUpdateListener { void onNewsUpdate(<News data to be passed>); }
-
Provide a registration facility on the background thread which gets the RSS feed
class <Background processing class name> { .... ArrayList<NewsUpdateListener> listeners = new ArrayList<NewsUpdateListener> (); .... public void setOnNewsUpdateListener (NewsUpdateListener listener) { // Store the listener object this.listeners.add(listener); } .... }
-
Fire the callback when news is available
.... for (listener : listeners) { listener.onNewsUpdate(<News data to be passed>); } ....
-
Register listener somewhere during initialization
.... <class <Background processing class object>.registerListener ( new OnNewsUpdateListener() { onNewsUpdate(<News Data>) { // process news data runOnUIThread(new Runnable() { public void run() { // refresh list view } } } } ....
Solution 2:
try this:
interface MyHandlerInterface
{
void onHandle(Object obj)
}
class myListClass
{
MyHandlerInterface myHandler;
public void setHandlerListener(MyHandlerInterface listener)
{
myHandler=listener;
}
protected void myEventFired(myObj)
{
if(myHandler!=null)
myHandler.onHandle(myObj);
}
}