I want to know what is SharedPreferencesCompat? and how is it different from SharedPreferences?
All ...Compat
classes are for backwards compatibility. Some bring new features to older devices that don't have them natively, some help in other ways to develop for old devices.
In this case, it provides a simplified way to call the apply
method which was added in API level 9.
You don't need that class, if your app doesn't support versions older than 9.
If you support older devices and were to do the following
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("key","val");
editor.apply();
you would get an error because that method does not exist on all devices you support. Working around this gets ugly. Unless you use SharedPreferencesCompat
:
...
editor.putString("key", "val");
SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
Source code will answer your question: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2_r1/com/android/common/SharedPreferencesCompat.java
Reflection utils to call SharedPreferences$Editor.apply when possible, falling back to commit when apply isn't available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With