Skip to content Skip to sidebar Skip to footer

Android Which Class Provide Definition To Sharedpreferences Interface

if look at SharedPreferences it clearly shows it's an interface in Android SDK. public interface SharedPreferences Can anyone help me understand it better that which class exactly

Solution 1:

It is an interface, there's no mistake in android's documentation. As you can see in SharedPreferences's source code too:

publicinterfaceSharedPreferences {

Digging in android's source code, we can see that Activity extends from ContextWrapper

publicclassActivityextendsContextThemeWrapperimplementsLayoutInflater.Factory2,
    Window.Callback, KeyEvent.Callback,
    OnCreateContextMenuListener, ComponentCallbacks2,
    Window.OnWindowDismissedCallback {

Looking at ContextWrapper.java, it calls getSharedPreferences function from Context class

Context mBase;

@OverridepublicSharedPreferencesgetSharedPreferences(String name, int mode) {
    return mBase.getSharedPreferences(name, mode);
}

Which is declared as an abstract function in Context.java,

/**
 * Interface to global information about an application environment.  This is
 * an abstract class whose implementation is provided by
 * the Android system.  It
 * allows access to application-specific resources and classes, as well as
 * up-calls for application-level operations such as launching activities,
 * broadcasting and receiving intents, etc.
 */publicabstractclassContext {

    publicabstract SharedPreferences getSharedPreferences(String name, int mode);

}

In conclusion SharedPreferences is implemented in a class(as every interface) on every Context implementation. If we take a look at the comments in Context's source code we can see that:

This is an abstract class whose implementation is provided by the Android system

And in case that you want more information about Context, here is way more info: What is Context in Android?

Solution 2:

getSharedpreference() is the function of ContextWrapper class. And ContextWrapper class is extended by Every Activity class.

When we use getSharedpreference() method then it is called by context class. It is in the context class object. But it returns the Sharedpreferences object. Shared preferences is not a class it is a interface. getSharedpreference() is use only reference of this interface.

Post a Comment for "Android Which Class Provide Definition To Sharedpreferences Interface"