我想在我的共享偏好设置中存储一个位置,并且可以编辑它,并在应用启动时打开它,谢谢,我有这个:
//load shared preferecnes
SharedPreferences sharedpreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
//note: here idk how to read the last value of position saved
//Log.v("lastposition", sharedPreferences );
// on edit preferences and save
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("position", New LatLang(30,40) );
editor.commit();
谢谢大家:)
最后编辑更改:
//load shared preferecnes
SharedPreferences sharedpreferences = getSharedPreferences(this,Context.MODE_PRIVATE);
// --> HERE IDK HOT LOAD LAST POSITIONS SAVED
// on edit preferences and save
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putDouble("position_lat", 30d );
editor.putDouble("position_lon", 40d);
editor.commit();
答案 0 :(得分:3)
sharedPreferences.getString("position", new LatLng(30,40).toString());
如果您的应用程序没有在" position"中保存信息,则需要加载默认值。这是LatLng(30,40)。 但是您无法保存复杂的对象,例如LatLng。您可以做的是保存/加载纬度和经度值:
//load shared preferecnes
SharedPreferences sharedpreferences = getSharedPreferences(this,Context.MODE_PRIVATE);
//note: here you load the saved latitude and longitude values into the variable with name "loaded_position":
LatLng loaded_position = new LatLng(0,0);
loaded_position.latitude= sharedpreferences.getFloat("position_lat", 15f);
loaded_position.longitude = sharedpreferences.getFloat("position_lon", 15f);
Log.v("lastposition", "loaded position: ("+loaded_position.latitude+","+loaded_position.longitude+")" );
// on edit preferences, save the LatLng Object:
SharedPreferences.Editor editor = sharedpreferences.edit();
LatLng currentPosition = new LatLng(30f,40f);
editor.putFloat("position_lat", (float) currentPosition.latitude );
editor.putFloat("position_lon", (float) currentPosition.longitude);
editor.commit();
此代码将您保存的编辑器(30,40)加载到loaded_position中。它应该在你第一次启动应用程序时加载15,15,因为在sharedPreferences的第一次启动时不会保存30,40。
答案 1 :(得分:1)