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

4

我想存储一个位置对象,正在尝试选择一种好的方法来实现。

请给我建议,如何做到这一点。

我正在使用以下代码,但是当我从首选项中获取位置时,位置返回如下...

Location[mProvider=STORAGE,mTime=0,mLatitude=30.0,mLongitude=76.0,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false,mSpeed=0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=false,mAccuracy=0.0,mExtras=null]

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

请查看以下内容:如何在Android SharedPreferences中保存/存储对象 - Protect Life Save Forests
我认为你不能将对象存储到sharedPreference中,你只能存储字符串和整数。尝试将你的对象拆分成一些字符串或整数。 - Mina Fawzy
它是否显示任何错误?KEY_LOCATION仅为字符串。 - Hanuman
没有显示任何错误,我已经在类中将KEY_LOCATION定义为字符串。 - Reyaj
4个回答

8

最佳解决方案: 将位置的经纬度参数提取为字符串,并将其保存在偏好设置中。根据您的用例,您也可以从位置中提取其他信息。

保存一个位置:

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

此答案所述。

这本应该不会崩溃,但在某些设备上却崩溃了。 如这里所提到的。


1
@ArthurMelo Gson方法可以正常工作,但是在一些设备上会崩溃,如“应用程序崩溃(有时)出现致命信号11(SIGSEGV),代码1”中所述。https://dev59.com/q1oU5IYBdhLWcg3wzZA1#37279407 - maveroid
不要使用这种方法,https://dev59.com/GqHia4cB1Zd3GeqPa-qk#47866646 - Kirill Vashilo
@KirillVashilo,已经提到Gson方法在某些设备上不起作用。因此,请使用纯序列化,如在此答案的第二个解决方案中已经提到的。 - maveroid

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

6
这种方法看起来可以运行,但是你会遇到本机Android崩溃(没有堆栈跟踪),因为位置(Location)没有默认构造函数,在使用Gson进行序列化时会导致问题。 - Lisandro
不要使用这种方法,https://dev59.com/GqHia4cB1Zd3GeqPa-qk#47866646 - Kirill Vashilo

0

如果您只关心经纬度,则可以使用以下答案。正如您在评论中所看到的,最受欢迎的答案是错误的。

您可以通过调用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();
    }

}

0

我需要保存Location的大部分成员,而不仅仅是纬度和经度。最终我编写了自己的Serializable类。请参见我的答案这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接