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. However, 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?
}
}