2012-09-09 50 views
4

我想存儲一個Location對象,並試圖選擇一個好方法來完成它。我只有一個小對象,我需要它是私有的,所以SharedPreferences或內部存儲對我來說最有意義。什麼是存儲位置對象的好方法?

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

這是一個合理的方法嗎?有沒有更好的辦法?

感謝您的任何建議。

+0

,我認爲這沒關係 –

+0

這是一個有趣的問題,這裏是一些聰明的答案http://stackoverflow.com/questions/5325310/store-objects-in-android – florianmski

回答

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; 
} 
相關問題