【问题标题】:Saving LatLng and List<Address> in SharedPreference在 SharedPreference 中保存 LatLng 和 List<Address>
【发布时间】:2014-10-24 04:48:29
【问题描述】:

是否可以在 SharedPreference 中保存 LatLng 和 List?从另一个活动我需要检索这个值。实现这一目标的最简单方法是什么?提前谢谢..

【问题讨论】:

    标签: android google-maps android-intent geolocation sharedpreferences


    【解决方案1】:

    这是我用于在共享首选项中存储复杂对象(String、Int 等除外)的代码。它也适用于列表。您需要将 gson 添加到您的项目 (https://code.google.com/p/google-gson/)。

    希望这会有所帮助!

    public <T> void putComplex(String key, T value){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String data = gson.toJson(value);
        Editor ed = getSettings(context).edit();
        ed.putString(key, data);
        ed.commit();
    }
    
    
    public <T> T getComplex(String key, Class<T> type){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String data = getSettings(context).getString(key, null);
        if (data==null){
            return null;
        }
        return gson.fromJson(data, type);
    }
    
    protected static SharedPreferences getSettings(Context context){
        SharedPreferences settings = context.getSharedPreferences(AppConfig.APP_ID, Context.MODE_PRIVATE);
        return settings;
    }   
    
    
    public static Address getAddress(Context context){
        return getComplex(SP_ADDRESS, Address.class);
    }
    
    public static void setAddress(Context context, Address address){
        putComplex(SP_ADDRESS, address);
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      相关资源
      最近更新 更多