How to trigger UI update on Activity when underlying datahandler receives data
I am creating an application which relies on data backend over Internet connection. This data is common between activities. Also, data will be kept refresh e.g. by updating it every two or three minutes. Therefore, I have created a data handler class, which should handle everything related to data downloading, parsing and such. Sometimes, it will receive command from Activity to refresh the data.
The problem is, how to refresh the UI in the activity when new data becomes available in the datahandler. If the datahandler was in activity, I could just post a handler for UI thread to update it. How开发者_开发技巧ever, I don't know how to do it from this underlying class. Any advice?
Here's the rough code for three classes:
/**
* The data handler class itself
*/
public class DataHandler {
Object data;
public void getData () {
// starts a thread (HTTP query) to get data
}
private class dataReceived (Object data) {
// receives data
this.data = data;
// TRIGGER updateUI() in MyActivity! HOW?
}
}
/**
* Application class. I'm planning to keep data handler here, and reference it from activities when required.
*/
public class MyApplication extends Application {
private DataHandler dataHandler;
public DataHandler getDataHandler() {
return dataHandler;
}
public void onCreate() {
DataHandler dataHandler = new DataHandler();
}
}
/**
* Activity
*/
public class MyActivity extends Activity {
DataHandler dataHandler;
public void onCreate(Bundle o) {
dataHandler = ((MyApplication) getApplication()).getDataHandler();
}
public void onResume() {
// trigger data refresh (OBS! This could also be by a button press etc.)
dataHandler.getData();
}
public void updateUI() {
// UPDATE UI
// should be called on DataHandler when data is received. HOW?
}
}
Register your activity as a listener to the DataHandler and when the thread recieves data invoke any listeners.
How are you presenting the data? If it's a ListView with an ArrayAdapter, then simply invoke the notifyDataSetChanged()
on it as you get an update.
You'll have to make sure you update the UI in an appropriate UI thread, of which there are many ways. One that springs to mind is you could create a blocking AsyncTask that receives the listener events, unblocks it's background thread and runs its publishProgress() to ensure the update happens on the UI.
精彩评论