一个好的存储Location对象的方法是什么?

4

这是一个有趣的问题,这里有一些聪明的答案:https://dev59.com/nm435IYBdhLWcg3wlRMf - florianmski
1个回答

3

当保存简单数据时,我更喜欢使用JSON对象,因为代码更简单,易于理解,对于未来的维护者而言更加友好,而不是操纵字节数组。由于这些对象很小,使用字符串代替字节数组的大小惩罚并不显著。

private static final String LATITUDE = "com.somepackage.name.LATITUDE";
private static final String LONGITUDE = "com.somepackage.name.LONGITUDE";

/**
 * Save a location/key pair.
 * 
 * @param key the key associated with the location
 * @param location the location for the key
 * @return true if saved successfully false otherwise
 */
public boolean saveLocation(String key, Location location) {
    LOG.info("Saving location");
    try {
        JSONObject locationJson = new JSONObject();

        locationJson.put(LATITUDE, location.getLatitude());
        locationJson.put(LONGITUDE, location.getLongitude());
        //other location data
        SharedPreferences.Editor edit = preferences.edit();
        edit.putString(key, locationJson.toString());
        edit.commit();
    } catch (JSONException e) {
        LOG.error("JSON Exception", e);
        return false;
    }

    LOG.info("Location {}  saved successfully at key: {}", preferences.getString(key, null),key);
    return true;
}

/**
 * Gets location data for a key.
 * 
 * @param key the key for the saved location
 * @return a {@link Location} object or null if there is no entry for the key
 */
public Location getLocation(String key) {
    LOG.info("Retrieving location at key {} ", key);
    try {
        String json = preferences.getString(key, null);

        if (json != null) {
            JSONObject locationJson = new JSONObject(json);
            Location location = new Location(STORAGE);
            location.setLatitude(locationJson.getInt(LATITUDE));
            location.setLongitude(locationJson.getInt(LONGITUDE));
            LOG.info("Returning location: {}" , location);
            return location;
        }
    } catch (JSONException e) {
        LOG.error("JSON Exception", e);
    }

    LOG.warn("No location found at key {}",  key);
    //or throw exception depending on your logic
    return null;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接