如何在SharedPreferences中存储和检索Location对象?

时间:2015-02-03 11:59:25

标签: java android sharedpreferences

我想存储一个Location对象,我正在尝试选择一个好方法。 请给我建议如何做到这一点

我正在使用此代码,但是当我从“首选项”获取位置时,“位置”会像这样返回...

位置[mProvider = STORAGE,MTIME = 0,mLatitude = 30.0,mLongitude = 76.0,mHasAltitude =假,mAltitude = 0.0,mHasSpeed =假,MSPEED = 0.0,mHasBearing =假,mBearing = 0.0,mHasAccuracy =假,mAccuracy = 0.0,mExtras =空]

/** Store Location object in SharedPreferences */
public void storeLocation(Context context, Location location) {
    SharedPreferences settings;
    Editor editor;
    try {
        JSONObject locationJson = new JSONObject();
        locationJson.put(LATITUDE, location.getLatitude());
        locationJson.put(LONGITUDE, location.getLongitude());

        settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
        editor = settings.edit();

        editor.putString(KEY_LOCATION, locationJson.toString());
        editor.commit();
        Log.i("location_util_store", "Location" + location);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/** Retrieve Location object from SharedPreferences
 * @return */
public Location getPrevLocation(Context context) {

    SharedPreferences settings;
    try {
        settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
        String jsonLocation = settings.getString(KEY_LOCATION, null);
        if (jsonLocation != null) {

            JSONObject locationJson = new JSONObject(jsonLocation);
            Location location = new Location("STORAGE");
            location.setLatitude(locationJson.getInt(LATITUDE));
            location.setLongitude(locationJson.getInt(LONGITUDE));
            Log.i("location_util_get", "Location" + location);
            return location;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

4 个答案:

答案 0 :(得分:6)

最佳解决方案:提取位置lat&将长参数作为字符串并将它们保存在prefs中。您也可以根据您的使用情况从位置提取其他信息。

保存位置: -

        if (location == null) {
            sharedPreferences.edit().removeKey("LOCATION_LAT").apply();
            sharedPreferences.edit().removeKey("LOCATION_LON").apply();
            sharedPreferences.edit().removeKey("LOCATION_PROVIDER").apply();
        } else {
            sharedPreferences.edit().putString("LOCATION_LAT", String.valueOf(location.getLatitude())).apply();
            sharedPreferences.edit().putString("LOCATION_LON", String.valueOf(location.getLongitude())).apply();
            sharedPreferences.edit().putString("LOCATION_PROVIDER", location.getProvider()).apply();
        }

检索位置: -

        String lat = sharedPreferences.getString("LOCATION_LAT", null);
        String lon = sharedPreferences.getString("LOCATION_LON", null);
        Location location = null;
        if (lat != null && lon != null) {
            String provider = sharedPreferences.getString("LOCATION_PROVIDER", null);
            location = new Location(provider);
            location.setLatitude(Double.parseDouble(lat));
            location.setLongitude(Double.parseDouble(lon));
        }
        return location;

错误的解决方案:使用Gson来保留您的位置:

保存位置:

String json = location == null ? null : new Gson().toJson(location);
sharedPreferences.edit().putString("Location", json).apply();

检索位置:

String json = sharedPreferences.getString("location", null);
return json == null ? null : new Gson().fromJson(json, Location.class);

this answer中所述。

这不应该崩溃,但它会在某些设备上崩溃。如上所述here

答案 1 :(得分:1)

解决了这个问题 商店位置对象:

SharedPreferences settings;
    Editor editor;
    try {

        settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
        editor = settings.edit();

        Gson gson = new Gson();
        String json = gson.toJson(location);
        editor.putString(KEY_LOCATION, json);
        editor.commit();

    } catch (Exception e) {
        e.printStackTrace();
    }

检索位置对象

SharedPreferences settings;
    try {
        settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);

        Gson gson = new Gson();
        String json = settings.getString(KEY_LOCATION, "");
        Location obj = gson.fromJson(json, Location.class);

        if (obj != null) {

            return obj;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

答案 2 :(得分:0)

如果只有Lat Long对您很重要,那么您可以使用以下答案。最流行的答案是错误的,你可以在评论中看到

您可以致电SharedPreferencesHelper.getInstance(context).setCurrentLocation(location);

来使用此功能
public class SharedPreferencesHelper {
    private static SharedPreferencesHelper sharedPreferencesHelper;
    private static SharedPreferences pref;
    private String CURRENT_LOCATION_LAT = "CURRENT_LOCATION_LAT";
    private String CURRENT_LOCATION_LONG = "CURRENT_LOCATION_LONG";

    public static SharedPreferencesHelper getInstance(Context context) {
        if (null == sharedPreferencesHelper) {
            pref = PreferenceManager.getDefaultSharedPreferences(context);
            sharedPreferencesHelper = new SharedPreferencesHelper();
        }
        return sharedPreferencesHelper;
    }

    public Location getCurrentLocation() {
        Location location = new Location("");//provider name is unnecessary
        location.setLatitude(getDouble(CURRENT_LOCATION_LAT));
        location.setLongitude(getDouble(CURRENT_LOCATION_LONG));
        return location;
    }

    public void setCurrentLocation(Location location) {
        setDouble(CURRENT_LOCATION_LAT, location.getLatitude());
        setDouble(CURRENT_LOCATION_LONG, location.getLongitude());
    }

    private double getDouble(String key) {
        return Double.longBitsToDouble(pref.getLong(key, Double.doubleToLongBits(0)));
    }

    private void setDouble(String key, double val) {
        SharedPreferences.Editor editor = pref.edit();
        editor.putLong(key, Double.doubleToRawLongBits(val));
        editor.commit();
    }

}

答案 3 :(得分:0)

我还需要保存Location及其大多数成员,而不仅仅是纬度和经度。我最终写了自己的Serializable类。请参阅我的答案here