Note that there are some explanatory texts on larger screens.

plurals
  1. POSharedPreferences not working across Activities
    text
    copied!<p>I'm trying to save some filters/state in one activity, and then use that data in the next activity.</p> <p>I'm using SharedPreferences, but it isn't working as I'd expected it to.</p> <pre><code> public class FilterActivity extends Activity { private static final String TAG = FilterActivity.class.getName(); EditText distanceEditor; @Override public void onPause() { super.onPause(); SharedPreferences preferences = getSharedPreferences(PreferenceKey.FILTER_PREFERENCES_NAME, MODE_WORLD_READABLE); String distance = distanceEditor.getText().toString(); preferences.edit().putString(PreferenceKey.DISTANCE, distance); preferences.edit().commit(); Log.i(TAG, "Wrote max-distance=" + distance); Log.i(TAG, "Preferences contains distance=" + preferences.getString(PreferenceKey.DISTANCE, "FAIL")); } public static class PreferenceKey { public static final String FILTER_PREFERENCES_NAME = "FilterActivity:" + "Filter_Preference_File"; public static final String DISTANCE = "FilterActivity:" + "DISTANCE"; } } </code></pre> <p>Then, the Activity that should use this preference:</p> <pre><code> public class MapActivity extends MapActivity { @Override public void onResume() { super.onResume(); SharedPreferences preferences = getSharedPreferences(FilterActivity.PreferenceKey.FILTER_PREFERENCES_NAME, MODE_WORLD_READABLE); String maxDistance = preferences.getString(FilterActivity.PreferenceKey.DISTANCE, "FAIL"); Log.i(TAG, "Read max-distance=" + maxDistance); } } </code></pre> <p>But the output I get is:</p> <pre><code> .FilterActivity( 4847): Wrote max-distance=99.9 .FilterActivity( 4847): Preferences contains distance=FAIL .MapActivity( 4847): Read max-distance=FAIL </code></pre> <p>Can anyone tell me what I'm doing wrong here?</p> <p>I am developing against API Level-8.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload