java - 存储 Location 对象的好方法是什么?

标签 java android persistence sharedpreferences

我想存储一个 Location 对象,并正在尝试选择一种好的方法来实现它。我只有一个小对象,我需要它是私有(private)的,所以到目前为止,SharedPreferences 或内部存储对我来说最有意义。

我看到一个对象可以是written to a bytearray, stored as a String in SharedPreferences, then written back to an object as described here .

这是一个合理的方法吗?有没有更好的办法?

感谢您的任何建议。

最佳答案

在保存简单数据时,我更喜欢使用 JSON 对象,因为与操作字节数组相比,代码对于 future 的维护者来说更简单、更容易理解。由于对象很小,因此使用字符串而不是字节数组的大小损失并不显着。

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

关于java - 存储 Location 对象的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342037/

相关文章:

java - 为什么 "java.lang.OutOfMemoryError: Java heap space"没有被抓到?

android - Intent + Share + Action_Send_Multiple + Facebook 不工作

java - 使用 jsoup 解析 HTML : differences between Android and Java

java - 如何确保 OpenJPA 中的非托管/托管对象身份?

java - 如何在protobuf3中将 map 添加到消息中

java - 通用数据类型 ID

java - app-debuk.apk停止工作

android - 为什么在使用 appcompat 和工具栏时我的自定义操作栏不显示 "match parent"?

persistence - 返回abap中持久化类的所有属性列表

java.lang.NoClassDefFoundError : javax/persistence/Persistence 错误