I need to set up a simple event listener to refresh a ListView
once in a while. The problem is I don\'t know how could I generate an event.
I know that
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
}
}
}
}
....
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);
}
}
It sounds like you need a Handler - (look-up android.os.Handler for details).
The sendMessageDelayed method will allow you to schedule when the message is sent to your handler.
A quick search pulled up a full example that should get you started: http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html
You can use android life cycle for that.
Create a signal interface, aka your event
interface NewsUpdateSignal{
void newsUpdateHandler(Mydata data);
}
Than register to it inside your activity or anywhere else you want, there could be many listeners to same Signal
.
class MyActivity extends Activity implements NewsUpdateSignal{
Signal<NewsUpateSignal> newsUpdateSignal = SignalsBag.inject(NewsUpateSignal.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
newsUpdateSignal.addListener(this);
}
@Override
public void newsUpdateHandler(final Mydata data){
//Do something here
}
}
And dispatch the signal when you need, from where ever you need.
Class A{
Signal<NewsUpateSignal> newsUpdateSignal = SignalsBag.inject(NewsUpateSignal.class);
void execute(){
// obtain the data somehow, and dispatch it, the callback will be invoked on the same thread
newsUpdateSignal.dispatcher.newsUpdateHandler(data);
}
}
Disclaimer: I am the author of android life cycle.