共享preferences不会在活动工作 [英] SharedPreferences not working across Activities

查看:104
本文介绍了共享preferences不会在活动工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想节省一些过滤器/状态在一个活动,然后使用该数据在接下来的活动。

I'm trying to save some filters/state in one activity, and then use that data in the next activity.

我使用的共享preferences,但我想它预计它不工作。

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().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";
  }
}

然后,应该使用这种preference活动:

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?

我对开发API级别-8。

I am developing against API Level-8.

推荐答案

在下面两行,

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

两个不同的共享preferences.Editor 正在返回秒。因此,值不被提交。相反,你必须使用:

two different SharedPreferences.Editors 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();

这篇关于共享preferences不会在活动工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆