SharedPReferences 没有恢复(只恢复默认值)

SharedPReferences are not restored (restore the default value only)

我有一个新的 Activity 是这样调用的:

 Intent i = new Intent(context, NewActivity.class);
....
                    context.startActivity(i);

此时 Activity 我必须 restore/save 基于 WebView 位置和 Seekbar(webview textzoom) positions/number.

的一些偏好

所以我做了这个:

public class LerLeiActivity extends AppCompatActivity  {
    SharedPreferences preferences;

    WebView wv;
    SeekBar skbar;

    HideOptionsMenu hdMenu;



    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.leituradalei);
        Intent intent = getIntent();
        wv = (WebView)this.findViewById(R.id.webView);
        skbar = (SeekBar) this.findViewById(R.id.seekFont);
        hdMenu = new HideOptionsMenu(this, wv);
        hdMenu.setWebViewURL(intent.getExtras().getString("path"));
        hdMenu.setSeekBarDefault(skbar);

        hdMenu.restoreLastPreference("preferences");

    }

这个 HideOptionsMenu 有这个方法:

WebView wv;
    Context context;
    SharedPreferences preferences;
    SeekBar skb;
public HideOptionsMenu(Context c, WebView webview) {
    this.context = c;
        this.wv = webview;

    }
    public void savePreferences(String leiID) {
        preferences = context.getSharedPreferences(leiID, 0);
        preferences.edit().putInt("fontZoom", skb.getProgress());
        preferences.edit().putInt("scrollY", wv.getScrollY());
        preferences.edit().commit();
        Log.d("shared", "saving");
        Log.d("shared", "fontZoom " + skb.getProgress());
        Log.d("shared", "scrollY " + wv.getScrollY());
    }
    public void restoreLastPreference(String leiID) {
        preferences = context.getSharedPreferences(leiID, 0);
        int lastZoom = preferences.getInt("fontZoom", 100);
        int lastY = preferences.getInt("scrollY", 0);

        Log.d("shared", "restoring");
        Log.d("shared", "fontZoom " + lastZoom);
        Log.d("shared", "scrollY " + lastY);
       // wv.getSettings().setTextZoom(lastZoom);
        //wv.setScrollY(lastY);

    }

我不明白为什么它一直加载存储的默认值,因为我在 Log.d

//loading
D/shared﹕ restoring
D/shared﹕ fontZoom 100
D/shared﹕ scrollY 0

//saving
D/shared﹕ saving
D/shared﹕ fontZoom 167
 D/shared﹕ scrollY 447

//after closing the Activity and opening it again
 D/shared﹕ restoring
D/shared﹕ fontZoom 100
D/shared﹕ scrollY 0

您应该只调用一次 edit() 函数,它 returns 一个 Editor 对象。因此,您应该执行以下操作:

Editor editor = preferences.edit();
editor.putInt("fontZoom", skb.getProgress());
editor.putInt("scrollY", wv.getScrollY());
editor.commit();

来自documentation

returns a new instance of the SharedPreferences.Editor interface, allowing you to modify the values in this SharedPreferences object.

因此,每次调用 edit() 时,您都会得到一个新实例,您不会提交更改。