I am writing an app to emulate a instrument for environmental monitoring using the GPSinformation to model the measurement data (https://github.com/sickel/measem). Within this app, I want the user to be able to define a point source at a given location. The lat / lon of this Location is to be stored in shared preferences. The point should either be defined by typing in lat and lon in settings (using the preferences API), or by reding in the gpslocation. The part with the settings works fine, I can also read in the location from the gps, but that dataset is overwritten by the data in the preference editor as soon as the app is paused.
My code for storing the values is:
SharedPreferences sp=this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putString("Latitude",lat);
ed.putString("Longitude",lon);
ed.apply();
I have also tried ed.commit(); in addition to the apply, but with the same result. How can I update what is seen from the preferences editor with what I am storing here?
My onPause does nothing with the preferences, it just does some other housekeeping:
public void onPause() {
super.onPause();
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
I am setting values from the preferences in this function
private void readPrefs(){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String ret=sharedPref.getString("Latitude", "1");
Double lat= Double.parseDouble(ret);
ret=sharedPref.getString("Longitude", "1");
Double lon= Double.parseDouble(ret);
there.setLatitude(lat);
there.setLongitude(lon);
}
This is beeing called from onResume() and onActivityResult(). I am using SettingsFragment to for the settingsmenu.
getPreferences
in the docs:
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
Since you're trying to get them in different activities, I suspect that you're actually referring to two different shared preferences, meaning two different files. Therefore I suggest you to use the same method to get your SharedPreferences
instance when getting and when putting. PreferenceManager.getDefaultSharedPreferences(context)
should do the work as well as context.getPreferences("NAME", Context.MODE_PRIVATE)
. If going for the second, I suggest to keep the name as a resource to make sure it's consistent.