SharedPreferences无法跨活动工作

时间:2011-03-26 12:05:05

标签: java android sharedpreferences

我正在尝试在一个活动中保存一些过滤器/状态,然后在下一个活动中使用该数据。

我正在使用SharedPreferences,但它没有像我预期的那样工作。


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";
  }
}

然后,应该使用此首选项的Activity:


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);
  }
}

但我得到的输出是:


.FilterActivity( 4847): Wrote max-distance=99.9
.FilterActivity( 4847): Preferences contains distance=FAIL
.MapActivity( 4847): Read max-distance=FAIL

谁能告诉我这里我做错了什么?

我正在针对API Level-8进行开发。

1 个答案:

答案 0 :(得分:7)

在以下两行中,

preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();

正在返回两个不同的SharedPreferences.Editor。因此,价值没有得到承诺。相反,你必须使用:

SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();