Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is SharedPreferencesCompat? vs SharedPreferences

Tags:

android

I want to know what is SharedPreferencesCompat? and how is it different from SharedPreferences?

like image 370
M. Usman Khan Avatar asked Nov 19 '15 08:11

M. Usman Khan


2 Answers

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);
like image 134
zapl Avatar answered Nov 18 '22 05:11

zapl


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.

like image 3
Access Denied Avatar answered Nov 18 '22 03:11

Access Denied