Java – SharedPreferences cannot work across activities
•
Java
I'm trying to save some filters / states in one activity and then use the data in the next activity
I'm using shared preferences, but it doesn't work as I expected
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";
}
}
Then, you should use the activity of this preference:
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);
}
}
But the output I get is:
.FilterActivity( 4847): Wrote max-distance=99.9 .FilterActivity( 4847): Preferences contains distance=FAIL .MapActivity( 4847): Read max-distance=FAIL
Who can tell me what I did wrong here?
I am developing for API level - 8
Solution
In the following two lines,
preferences.edit().putString(PreferenceKey.DISTANCE,distance); preferences.edit().commit();
Returning two different SharedPreferences Editors. Therefore, value is not promised Instead, you must use:
SharedPreferences.Editor spe = preferences.edit(); spe.putString(PreferenceKey.DISTANCE,distance); spe.commit();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
