【发布时间】:2015-04-02 14:47:39
【问题描述】:
我想存储一个 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;
}
【问题讨论】:
-
我认为你不能将对象存储到 sharedPereference 中,你只能存储字符串和 int 尝试将你的对象分解为一些字符串或整数
-
是否显示任何错误。 KEY_LOCATION 只是字符串。
-
没有显示任何错误,我已将 KEY_LOCATION 定义为类中的字符串
标签: java android sharedpreferences