使用 Firebase 为两个活动仅检索一次数据

Retrieve data only once for two activities using Firebase

我是 Android 开发的新手,目前(正在尝试)为学校相关项目编写应用程序。

我在 Firebase 数据库中存储了一些数据,我使用 onChildEvent() 方法检索这些数据,我想在两个 Activity 中使用这些数据,一个是 GoogleMap,另一个是 List。我的问题是,即使我在检索数据时没有特别的问题,但在我看来,对相同的数据执行两次并不是正确的方法,但我无法帮助找到合适的解决方案。

我考虑过在其中一个活动中检索数据并使用意图将其传递给另一个活动,但由于这两个活动没有直接关联(没有办法也没有理由从一个活动转到另一个活动),我不认为这是个好主意。

PS: 英语不是我的母语,如果有什么不清楚的,尽管问,我会尽力重新表述;)

就像@Dima Rostopira 所说的那样,您可以实现一个单例,它在应用程序的整个过程中只存在一次。

带有 "Location" 对象的示例:

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);
    }
}

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
}