I'm trying to save some filters/state in one activity, and then use that data in the next activity.
I'm using SharedPreferences, but it isn't working as I'd expected it to.
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().putS开发者_如何学JAVAtring(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, the Activity that should use 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
Can anyone tell me what I'm doing wrong here?
I am developing against API Level-8.
In the following two lines,
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editor
s are being returned. Hence the value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();
精彩评论