什么时候调用editor.apply?

时间:2016-06-23 14:51:47

标签: java android sharedpreferences

在我的应用程序中,我有多达20个假期可由用户定义,当将它们保存到共享首选项编辑器时,我将其设置如下:

String checkhold = "0";
String holodate = g.getData82();// string is either "0" if no holidays entered, or, for example, "1,1,7,4,12,25, if January 1st, July 4th and December 25th is entered

if (!holodate.equals("0")) {

    checkhold = holodate;
    int value = 0;
    String splitHere = "[,]";
    String[] sToken = holodate.split(splitHere);
    int count = holodate.length() - checkhold.replace(",", "").length();
    g.setData92(emp, count);
    double holidayNumber = count * 0.5;
    passeditor.putDouble(holnums, holidayNumber);

if (count >= 0) {
    value = Integer.parseInt(sToken[0]);
    g.setData90(0, value);
    passeditor.putInt(holmonth1, value);passeditor.apply();
    value = Integer.parseInt(sToken[1]);
    g.setData91(0, value);
    passeditor.putInt(holday1, value);passeditor.apply();
    }

    if (count >= 2) {
    value = Integer.parseInt(sToken[2]);
    g.setData90(1, value);
    passeditor.putInt(holmonth2, value);passeditor.apply();
    value = Integer.parseInt(sToken[3]);
    passeditor.putInt(holday2, value);passeditor.apply();
    g.setData91(1, value);
    }
//....continue 18 more code blocks
}

正如你所看到的,我称passitor.apply为40次, 但我想知道的是,我需要在每个passitor.put后调用passitor.apply,在这20个代码块的情况下,或者我可以在每个代码块的末尾调用一次,或者我可以只调用一次在所有20个代码块的末尾? 只是试图消除不必要的代码

2 个答案:

答案 0 :(得分:3)

当您想要保存对SharedPreferences的更改时,请将其调用 - 您可以在编辑结束时调用一次。

答案 1 :(得分:1)

您可以按照以下操作

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","name");
editor.putInt("integer",22);
.
.
.
editor.apply();//At the end save all by calling editor.apply()