I'm new to Android development and currently (trying to) code an application for a school related project.
I have some data stored in a Firebase Database that I retrieve using the onChildEvent() method, and I want to use this data in two Activities, one is a GoogleMap and the other is a List. My problem is, even though I have no particular problem retrieving the data, it seems to me that doing it twice for the same data is not the right way of doing it, but i can't help to find the appropriate solution.
I thought about retrieving the data in one of the activities and passing it to the other using an intent, but since the two activities are not directly linked (no way and no reason of going from one to the other), I don't think this is a good idea.
PS: English isn't my native language, if anything isn't clear, just ask and I'll do my best to reformulate ;)
Like @Dima Rostopira says, you could implement a Singleton, which exists once over the course of an application.
Example with "Location" object:
final class LocationModel {
private Context mContext;
/** List of locations */
private ArrayList<Location> mLocations;
/** Static instance of LocationModel, accessible throughout the scope of the applicaton */
private static final LocationModel sLocationModel = new LocationModel();
private LocationModel() {}
/**
* Returns static instance of LocationModel
*/
public static LocationModel getLocationModel() {
return sLocationModel;
}
/**
* Sets context, allowed once during application
*/
public void setContext(Context context) {
if (mContext != null) {
throw new IllegalStateException("context has already been set");
}
mContext = context.getApplicationContext();
}
/**
* Asynchronously loads locations using callback. "forceReload" parameter can be
* set to true to force querying Firebase, even if data is already loaded.
*/
public void getLocations(OnLocationsLoadedCallback callback, boolean forceReload) {
if (mLocations != null && !forceReload) {
callback.onLocationsLoaded(mLocations);
}
// make a call to "callback.onLocationsLoaded()" with Locations when query is completed
}
/**
* Callback allowing callers to listen for load completion
*/
interface OnLocationsLoadedCallback {
void onLocationsLoaded(ArrayList<Locations> locations);
}
}
Usage inside of an Activity:
MainActivity implements OnLocationsLoadedCallback {
...
public void onCreate(Bundle savedInstanceState) {
...
LocationModel.getLocationModel().getLocations(this);
...
}
@Override
public void onLocationsLoaded(ArrayList<Locations> location) {
// Use loaded locations as needed
}