86 Android Shared Preferences Tutorial | SharedPreferences in android | Part 1
#SharedPreferences: Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory()
The primary purpose is to store user-specified configuration details, such as user specific settings, keeping the user logged into the application.
To get a handle to a preference file, and to read, write, and manage preference data, use the SharedPreferences class.
shared means to distribute data within and preference means something important or preferable.
Shared Preference can be used to save primitive data type: string, long, int, float and Boolean.
The Android framework manages the shared preferences file itself. The file is accessible to all the components of your app, but it is not accessible to other apps. The data you save to shared preferences is different from the data in the saved activity state.
Data in a saved activity instance state is retained across activity instances in the same user session.
Shared preferences persist across user sessions.
Shared preferences persist even if your app stops and restarts, or if the device reboots.
What Is Preference File?
A preference file is actually a xml file saved in internal memory of device.
Every application have some data stored in memory in a directory data/data/application package name i.e data/data/com.myapp.helloapp so, whenever getSharedPreferences(String name,int mode) method get called it validates the file that if it exists or it doesn’t then a new xml is created with passed name.
Two Different Ways To work with Shared Preference:
1) Using Activity based preferences
2) creating custom preferences.
1) Activity Preferences:
For activity preferences developer have to call method getPreferences (int mode) available in Activity class
Use only when one preference file is needed in Activity
It doesn’t require name as it will be the only preference file for this activity
The function getPreferences(int mode) call the other function used to create custom preferences i.e getSharedPreferences(String Pref_name,int mode).
2) Custom Preferences:
Developer needs to use getSharedPreferences(String name,int mode) for custom preferences.
Used in cases when more than one preference file required in Activity.
Name of the preference file is passed in first parameter
Custom Preferences can be created by calling function getSharedPreferences(String name,int mode), it can be called from anywhere in the application with reference of Context.
To create activity based preferences or custom preferences developer have to pass MODE to inform to android app know about privacy of preference file.
Types of Mode in Shared Preference:
1) Context.MODE_PRIVATE – default value (Not accessible outside of your android application)
2) Context.MODE_WORLD_READABLE – readable to other apps
3) Context.MODE_WORLD_WRITEABLE – read/write to other apps
4) MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded
5) MODE_APPEND: This will append the new preferences with the already existing preferences
6) MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default
Creating Shared Preference:
To create shared preference developer needs to call
getPreferences(int mode) or
getSharedPreferences(String name,int mode) method. Both of the function return SharedPreferences object to deal with save and get values from preference file.
Creating Shared Preferences:
To create one shared preferences file per app.
When you want to get the values, call getSharedPreferences() method.
Shared Preferences provide modes of storing the data (private mode and public mode). It is for the backward compatibility- use only MODE_PRIVATE to be secure.
To create or to get access shared prepferences to the developer needs to call one of the three methods:
getPreferences() : used from within your Activity, to access activity-specific preferences
getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences
getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework
getSharedPreferences(String PREFS_NAME,int mode) method.
PREFS_NAME is the name of the file. mode is the operating mode.
However there can multiple preference files so all the preference files can be read and write using SharedPreferences class.
Nested classes of Shared Preferences:
SharedPreferences.Editor: Interface used to write(edit) data in SharedPreference file. Once editing has been done, one must commit() or apply() the changes made to the file.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «86 Android Shared Preferences Tutorial | SharedPreferences in android | Part 1», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.