Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/179.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在SharedReferences中存储和检索位置对象?_Java_Android_Sharedpreferences - Fatal编程技术网

Java 如何在SharedReferences中存储和检索位置对象?

Java 如何在SharedReferences中存储和检索位置对象?,java,android,sharedpreferences,Java,Android,Sharedpreferences,我想存储一个Location对象,我正在尝试选择一种好的方法。 请给我建议,如何做到这一点 我正在使用这段代码,但当我从首选项中获取位置时,位置会像这样返回 位置[mProvider=存储,mTime=0,mLatitude=30.0,mLagtude=76.0,mHasAltude=false,mHasSpeed=false,mHasPeed=0.0,mHasBearing=false,mHasAccuracy=false,mHasAccuracy=false,mAccuracy=0.0,mX

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

我正在使用这段代码,但当我从首选项中获取位置时,位置会像这样返回

位置[mProvider=存储,mTime=0,mLatitude=30.0,mLagtude=76.0,mHasAltude=false,mHasSpeed=false,mHasPeed=0.0,mHasBearing=false,mHasAccuracy=false,mHasAccuracy=false,mAccuracy=0.0,mXtras=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;
}
已解决此问题
存储位置对象:

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

最佳解决方案:将位置lat&long参数提取为字符串,并将其保存在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;
检索位置:-

        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);
检索位置:

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);
如中所述


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

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

您可以通过调用
SharedReferencesHelper.getInstance(上下文).setCurrentLocation(位置)来使用它


我需要将
位置
与它的大多数成员一起保存,而不仅仅是纬度和经度。我最终编写了自己的
Serializable
类。请看我的答案。

请看一看,我认为您不能将对象存储到sharedPereference中,您只能存储string和int尝试将对象拆分为一些字符串或整数它是否显示任何错误。KEY_位置仅为字符串。没有显示任何错误,我已将KEY_位置定义为类中的字符串。这似乎可行,但您将获得本机android崩溃(没有stacktrace),因为LOCATION没有默认构造函数,并且在使用Gson序列化时会导致问题。不要使用这种方法,@ArthurMelo Gson方法可行,但“应用程序崩溃(有时)与致命信号11(SIGSEGV),代码1”中提到的某些设备上的应用程序崩溃。不要使用这种方法,@KirillVashilo,已经提到Gson方法在某些设备上不起作用。因此,使用本答案第二个解决方案中已经提到的普通序列化。