SharedPReferences未恢复(仅恢复默认值)

时间:2015-06-24 15:32:10

标签: android sharedpreferences

我以这种方式调用了一个新的Activity:

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

在此活动中,我必须根据WebView位置和Seekbar(webview textzoom)位置/编号恢复/保存一些首选项。

所以我这样做了:

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

1 个答案:

答案 0 :(得分:1)

您应该只调用一次edit()函数,它会返回一个Editor对象。所以你应该做到以下几点:

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

来自documentation

  

返回SharedPreferences.Editor接口的新实例,允许您修改此SharedPreferences对象中的值。

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