Java 什么';存储位置对象的好方法是什么?
我想存储一个位置对象,并试图选择一个好的方法来做到这一点。我只有一个小对象,我需要它是私有的,所以共享引用或内部存储对我来说是最有意义的 我看到一个物体是可以移动的 这是合理的做法吗?有更好的办法吗Java 什么';存储位置对象的好方法是什么?,java,android,persistence,sharedpreferences,Java,Android,Persistence,Sharedpreferences,我想存储一个位置对象,并试图选择一个好的方法来做到这一点。我只有一个小对象,我需要它是私有的,所以共享引用或内部存储对我来说是最有意义的 我看到一个物体是可以移动的 这是合理的做法吗?有更好的办法吗 谢谢您的建议。在保存简单数据时,我更喜欢使用JSON对象,因为对于未来的维护人员来说,代码比操作字节数组更简单、更容易理解。由于对象很小,因此使用字符串而不是字节数组的大小代价并不显著 private static final String LATITUDE = "com.somepackage.n
谢谢您的建议。在保存简单数据时,我更喜欢使用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;
}
这是一个有趣的问题,这里有一些聪明的答案