SharedPreferences未更新

时间:2014-04-13 03:17:20

标签: android settings sharedpreferences

我仍然在安卓的脚下湿透了。我试图保存一个季节和一年代表默认的“学期”,但我的修改不适用。我已经记录并确认我的settings.edit().putInt()语句试图输入我期望的值。

但是当我重新加载屏幕时,我发现我的偏好设置使用了提供的默认值。为什么我的价值观没有采取?感谢。

public class SetSemester扩展了ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_set_semester);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new SetSemesterFragment()).commit();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.set_semester, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class SetSemesterFragment extends Fragment {

    View rootView;
    SharedPreferences settings;
    int YEAR_DEFAULT_VALUE = AddCourse.thisYear - AddCourse.baseYear;
    int SEASON_DEFAULT_VALUE = 0;

    String year_key;
    String season_key; 

    static int baseYear=2005;
    static int thisYear = Calendar.getInstance().get(Calendar.YEAR);



    public SetSemesterFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_set_semester,
                container, false);

        year_key = getResources().getString(R.string.year_pref_str);
        season_key = getResources().getString(R.string.season_pref_str);

        Button b = (Button) rootView.findViewById(R.id.apply_semester_btn);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                applySemester(v);
            }
        });

        settings = this.getActivity().getSharedPreferences(getResources().getString(R.string.main_prefs_file), 0);

        int curYear = settings.getInt(year_key, YEAR_DEFAULT_VALUE);
        int curSeason = settings.getInt(season_key, SEASON_DEFAULT_VALUE);

        System.out.println("stored values..." + curYear + "  " + curSeason);
        //Year Spinner
        ArrayList<String> years = new ArrayList<String>();
        for (int i = baseYear; i <= 2030; i++)
        {
            years.add(Integer.toString(i));
        }
        ArrayAdapter<String> adapter_year = new ArrayAdapter<String>(this.getActivity(),
                android.R.layout.simple_spinner_item, years);

        Spinner spinYear = (Spinner)rootView.findViewById(R.id.year_spinner);
        adapter_year.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinYear.setAdapter(adapter_year);
        spinYear.setSelection(curYear);

        //Semester Spinner
        Spinner spinner = (Spinner) rootView.findViewById(R.id.semester_spinner);
         // Create an ArrayAdapter using the string array and a default spinner layout
         ArrayAdapter<CharSequence> adapter_spinner = ArrayAdapter.createFromResource(this.getActivity(),
         R.array.semester_spinner, android.R.layout.simple_spinner_item);
         // Specify the layout to use when the list of choices appears
         adapter_spinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         // Apply the adapter to the spinner
         spinner.setAdapter(adapter_spinner);
         spinner.setSelection(curSeason);

        return rootView;
    }

    public void applySemester(View v){

        Spinner semesterSpin = (Spinner)rootView.findViewById(R.id.semester_spinner);
        Spinner yearSpin = (Spinner)rootView.findViewById(R.id.year_spinner);

        //ToStrings
        int year = yearSpin.getSelectedItemPosition();
        int season = semesterSpin.getSelectedItemPosition();
        System.out.println(year + " " + season);
        settings.edit().putInt(year_key, year);
        settings.edit().putInt(season_key, season);
        settings.edit().apply();
    }

}

}

1 个答案:

答案 0 :(得分:7)

问题在以下三个陈述中:

settings.edit().putInt(year_key, year);
settings.edit().putInt(season_key, season);
settings.edit().apply();

SharedPrefences edit方法返回一个新的编辑器。在此编辑器上执行的所有操作都将保留在内存中,并仅在调用apply方法时保存到文件中。 因此,每次调用edit()时,都会对新创建的编辑器执行操作。

要解决此问题,请使用以下代码替换上述3行:

SharedPreferences.Editor edit = settings.edit();
edit.putInt(year_key, year);
edit.putInt(season_key, season);
edit.apply();