'SharedPreferences Integers wont save

I want to save two integers in SharedPreferences but they won't get saved. I have a RangeSlider with a min and max value. The slider values definetly get updated but when I save them and call sharedPreferences.getInt(...); the values are not saved. Shared Preferences has still the default value. Does anybody see what my mistake is?

Thanks in advance!

public class SettingsFragment extends Fragment {

    private FragmentSettingsBinding binding;
    private SettingsViewModel settingsViewModel;
    private SharedPreferences sharedPreferences;

    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.binding = FragmentSettingsBinding.inflate(inflater, container, false);
        this.settingsViewModel = new ViewModelProvider(this).get(SettingsViewModel.class);
        this.settingsViewModel.setRepository(((MainActivity)getActivity()).getRepository());

        sharedPreferences =  requireActivity().getSharedPreferences(getString(R.string.app_name),Context.MODE_PRIVATE);

        this.binding.sliderMinMaxSetting.addOnChangeListener(new RangeSlider.OnChangeListener() {
            @Override
            public void onValueChange(@NonNull @NotNull RangeSlider slider, float value, boolean fromUser) {
                sharedPreferences.edit().putInt(getString(R.string.settingMin), Math.round(slider.getValues().get(0)));
                sharedPreferences.edit().putInt(getString(R.string.settingMax), Math.round(slider.getValues().get(1)));
                sharedPreferences.edit().commit();

                int min = sharedPreferences.getInt(getString(R.string.settingMin), getResources().getInteger(R.integer.settingMinDefaultValue));
                Log.d("SettingsFragment", "minSharedPref : " + min + ", minSlider : " + Math.round(slider.getValues().get(0))); // Result: slider value is updated but not shared preferences

            }
        });       

        this.binding.buttonResetSettings.setOnClickListener(v -> {

            sharedPreferences.edit().putInt(getString(R.string.settingMin), getResources().getInteger(R.integer.settingMinDefaultValue));
            sharedPreferences.edit().putInt(getString(R.string.settingMax), getResources().getInteger(R.integer.settingMaxDefaultValue));

            sharedPreferences.edit().commit();

            updateUiWithSharedPrefData();

            Toast.makeText(getContext(), "Settings reset", Toast.LENGTH_SHORT).show();
        });

        updateUiWithSharedPrefData();

        return this.binding.getRoot();
    }


    private void updateUiWithSharedPrefData(){

        Log.d("SettingsFragment", "min / max : " + sharedPreferences.getInt(getString(R.string.settingMin), getResources().getInteger(R.integer.settingMinDefaultValue)) + " / " + sharedPreferences.getInt(getString(R.string.settingMax), getResources().getInteger(R.integer.settingMaxDefaultValue)));

        List<Float> floats = new ArrayList<>();
        float min = (float) sharedPreferences.getInt(getString(R.string.settingMin), getResources().getInteger(R.integer.settingMinDefaultValue));
        float max = (float) sharedPreferences.getInt(getString(R.string.settingMax), getResources().getInteger(R.integer.settingMaxDefaultValue));

        floats.add(min);
        floats.add(max);

        binding.sliderMinMaxSetting.setValues(floats);

    }
}

Thanks for the answers. This is the solution:

sharedPreferences.edit()
                        .putInt(getString(R.string.settingMin), Math.round(slider.getValues().get(0)))
                        .putInt(getString(R.string.settingMax), Math.round(slider.getValues().get(1)))
                        .commit();


Solution 1:[1]

The accepted answer is a correct way of doing this, but you can also simply make sure you use the same Editor instance if you want multiple putX calls without chaining the calls into one line of code, like this:

SharedPreferences.Editor ed = sharedPreferences.edit();
ed.putInt("somekey", 1);
ed.putInt("otherkey",2);
ed.apply(); // or ed.commit()

The reason the original code did not work is because each time you call edit() it returns a brand new Editor instance. It was the equivalent of calling

SharedPreferences.Editor ed1 = sharedPreferences.edit();
ed1.putInt("somekey", 1); // this change never gets committed because you never call commit on 'ed1'

SharedPreferences.Editor ed2 = sharedPreferences.edit();
ed2.putInt("otherkey", 2); // this change never gets committed because you never call commit on 'ed2'

SharedPreferences.Editor ed3 = sharedPreferences.edit();
ed3.commit() // this does nothing since ed3 had no changes

Solution 2:[2]

Replace your SharedPreferences initialization with this:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Prajjwal Srivastav