- SharedPreferences
- Сохранение значений параметров
- Чтение значений параметров
- Очистка значений
- Методы getStringSet() и putStringSet()
- Удаление файла
- Метод getPreferences() — Сохранение состояния активности
- Сохранение настроек на SD-карту
- Я у тебя первый?
- Запомнить пользователя
- Запомнить состояние переключателей
- getDefaultSharedPreferences()
- Удаляем файл настроек
- Shared Preferences in Android with Example
- How is Shared Preferences different from Saved Instance State?
- How to Create Shared Preferences?
- Nested classes of Shared Preferences
- Following are the methods of Shared Preferences
- What is shared preference in Android-Kotlin?
- Introduction
- Handling shared preferences
- Writing to shared preference
- Reading from shared preference
- commit() and apply()
- Conclusion
SharedPreferences
Чтобы получить экземпляр класса SharedPreferences для получения доступа к настройкам в коде приложения используются три метода:
- getPreferences() — внутри активности, чтобы обратиться к определённому для активности предпочтению;
- getSharedPreferences() — внутри активности, чтобы обратиться к предпочтению на уровне приложения;
- getDefaultSharedPreferences() — из объекта PreferencesManager, чтобы получить общедоступную настройку, предоставляемую Android.
Все эти методы возвращают экземпляр класса SharedPreferences, из которого можно получить соответствующую настройку с помощью ряда методов:
- getBoolean(String key, boolean defValue)
- getFloat(String key, float defValue)
- getInt(String key, int defValue)
- getLong(String key, long defValue)
- getString(String key, String defValue)
Обратите внимание, что тип double не поддерживается.
Чтобы создать или изменить Общие настройки, нужно вызвать метод getSharedPreferences в контексте приложения, передав имя общих настроек (имя файла):
По умолчанию используется MODE_PRIVATE — только приложение имеет доступ к настройкам. Также существуют другие режимы, с которыми практически не встречался.
- MODE_APPEND — присоединяет новые настройки к существующим
- MODE_ENABLE_WRITE_AHEAD_LOGGING
- MODE_MULTI_PROCESS
- MODE_WORLD_READABLE — позволяет другим приложениям читать настройки
- MODE_WORLD_WRITEABLE — позволяет другим приложениям записывать новые настройки
Для любознательных могу добавить, что файлы настроек хранятся в каталоге /data/data/имя_пакета/shared_prefs/имя_файла_настроек.xml. Поэтому в отладочных целях, если вам нужно сбросить настройки в эмуляторе, то при помощи перспективы DDMS, используя файловый менеджер, зайдите в нужную папку, удалите файл настроек и перезапустите эмулятор, так как эмулятор хранит данные в памяти, которые он сбрасывает в файл. На устройстве вы можете удалить программу и поставить ее заново, то же самое можно сделать и на эмуляторе, что бывает проще, чем удалять файл настроек вручную и перезапускать эмулятор.
Если открыть файл настроек текстовым редактором, то можно увидеть приблизительно такое:
В данном случае в настройках хранятся только строковые значения.
Сохранение значений параметров
Для удобства создадим константу для имени файла настроек, например:
Далее нужно создать параметры, которые вы хотите сохранять в настройках. Удобнее их сделать константами:
Когда вы определили названия параметров, то можете сохранять любые значения этих параметров. Для этого создаём переменную, представляющую экземпляр класса SharedPreferences:
Внутри метода onCreate() вы инициализируете эту переменную:
Вы передаёте в указанный метод название вашего файла (он будет создан автоматически) и стандартное разрешение, дающее доступ только компонентам приложения.
Чтобы внести изменения в настройки (редактировать), нужно использовать класс SharedPreferences.Editor. Получить объект Editor можно через вызов метода edit объекта SharedPreferences, который вы хотите изменить. После того, как вы внесли все необходимые изменения, вызовите метод commit() или apply() объекта Editor, чтобы изменения вступили в силу. Метод apply() появился в API 9 и работает в асинхронном режиме, что является более предпочтительным вариантом. Метод commit() приходится использовать для старых версий и кроме того, он возвращает значение true в успешном случае и false в случае ошибки. Если вам надо отслеживать ошибки, то используйте его.
Предположим, что у нас есть два текстовых поля, где пользователь должен ввести имя кота и его и возраст. Чтобы сохранить параметр, нужно получить текст, который ввел пользователь, через метод getText().toString():
Получив нужный текст, сохраняем его через метод putString() (есть также putLong(), putBoolean() и т.п.):
Как правило, параметры сохраняют в методах активности onPause() или onStop() в тех случаях, когда данные требуются сохранить между запусками приложения. Но могут быть и другие сценарии.
Чтение значений параметров
Для считывания данных при загрузке приложения обычно используют методы onCreate() или onResume(). Нам нужно получить доступ к настройкам программы и проверить, есть ли среди них нужный нам параметр. Нас интересует ключ Nickname. Если мы его найдём, то загрузим его значение в текстовое поле.
В этих строчках кода мы проверили существование параметра APP_PREFERENCES_NAME и получили его значение через getString(), передавая ключ и значение по умолчанию (используется в том случае, если для данного ключа пока что не сохранено никакое значение). Осталось только загрузить полученный результат в текстовое поле.
Аналогично поступаем и с другими параметрами через методы get () (getLong, getBoolean() и т.д.).
Если вам ещё не понятно, то ниже исходный код:
Показать код (щелкните мышкой)
Можно получить ассоциативный массив со всеми ключами и значениями через метод getAll(). После этого можно проверить наличие конкретного ключа с помощью метода contains().
Очистка значений
Для очистки значений используйте методы SharedPreferences.Editor.remove(String key) и SharedPreferences.Editor.clear().
Методы getStringSet() и putStringSet()
Начиная с API 11, у класса SharedPreferences появился новый метод getStringSet(), а у класса SharedPreferences.Editor родственный ему метод putStringSet(). Данные методы позволяют работать с наборами строк, что бывает удобно при большом количестве настроек, которые нужно сразу записать или считать.
Удаление файла
Как я уже сказал, файл настроек хранится в /data/data/имя_пакета/shared_prefs/имя_файла_настроек.xml. Вы можете удалить его программно, например так:
Учтите, что данные могут оставаться в памяти и временном файле *.bak. Поэтому, даже после удаления файла, он может заново воссоздаться. Вообще удалять файл не рекомендуется. Он автоматически удалится при удалении самой программы.
Метод getPreferences() — Сохранение состояния активности
Если вы хотите сохранить информацию, которая принадлежит активности и не должна быть доступна другим компонентам (например, переменным экземпляра класса), вы можете вызвать метод Activity.getPreferences() без указания названия Общих настроек. Доступ к возвращённому ассоциативному массиву Общих настроек ограничен активностью, из которой он был вызван. Каждая активность поддерживает только один безымянный объект Общих настроек.
Сохранение настроек на SD-карту
Сам файл с настройками хранится в системе и обычному пользователю он не виден. Если вам понадобится получить все значения, хранимые в настройках, то вы можете считать все данные при помощи метода getAll() и записать их в файл, который можно сохранить на SD-карте:
Я у тебя первый?
Предположим, вы хотите выводить пользователю какую-то информацию при первом запуске приложения (краткую инструкцию, заставку и т.п.).
Запомнить пользователя
Иногда требуется запомнить имя пользователя или другие данные (пин-код, номер телефона и т.д.). В этом случае вам также подойдут предпочтения, когда вы просто сохраняете нужную строку из текстового поля:
Запомнить состояние переключателей
Если нужно запомнить состояние переключателей, то код может быть таким. Создадим разметку с тремя переключателями.
Код, который отслеживает выбор переключателя и записывает состояние в настройки.
getDefaultSharedPreferences()
В используемых примерах я использовал getSharedPreferences() с придумыванием имени файла для хранения настроек. Этот способ придаёт гибкости в том случае, когда вам нужно создать несколько отдельных файлов. Но если вам нужен один файл, то можно ничего не придумывать, а использовать метод getDefaultSharedPreferences() из объекта PreferencesManager. Система сама сгенерирует имя файла из имени вашего пакета с добавлением слова _preferences. Вот как выглядит связка из трёх методов в исходниках Android (обратите внимание на выделенный текст).
Поэтому примеры можно переделать следующим образом.
Удаляем файл настроек
В API 24 появился новый метод, позволяющий удалить сам файл настроек. До этого можно было удалить своими силами, зная его местоположение. Поэтому универсальный код будет приблизительно следующим.
Источник
Shared Preferences in Android with Example
One of the most Interesting Data Storage options Android provides its users is Shared Preferences. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage. Shared Preferences can be thought of as a dictionary or a key/value pair. For example, you might have a key being “username” and for the value, you might store the user’s username. And then you could retrieve that by its key (here username). You can have a simple shared preference API that you can use to store preferences and pull them back as and when needed. Shared Preferences class provides APIs for reading, writing, and managing this data. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Shared Preferences are suitable in different situations. For example, when the user’s settings need to be saved or to store data that can be used in different activities within the app. As you know, onPause() will always be called before your activity is placed in the background or destroyed, So for the data to be saved persistently, it’s preferred to save it in onPause(), which could be restored in onCreate() of the activity. The data stored using shared preferences are kept private within the scope of the application. However, shared preferences are different from that activity’s instance state.
How is Shared Preferences different from Saved Instance State?
Saved Instance State
How to Create Shared Preferences?
The first thing we need to do is to create one shared preferences file per app. So name it with the package name of your app- unique and easy to associate with the app. When you want to get the values, call the getSharedPreferences() method. Shared Preferences provide modes of storing the data (private mode and public mode). It is for backward compatibility- use only MODE_PRIVATE to be secure.
public abstract SharedPreferences getSharedPreferences (String name, int mode)
This method takes two arguments, the first being the name of the SharedPreference(SP) file and the other is the context mode that we want to store our file in.
MODE_PUBLIC will make the file public which could be accessible by other applications on the device
MODE_PRIVATE keeps the files private and secures the user’s data.
MODE_APPEND is used while reading the data from the SP file.
Nested classes of Shared Preferences
- SharedPreferences.Editor: Interface used to write(edit) data in the SP file. Once editing has been done, one must commit() or apply() the changes made to the file.
- SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing value. This callback will be run on your main thread.
Following are the methods of Shared Preferences
- contains(String key): This method is used to check whether the preferences contain a preference.
- edit(): This method is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
- getAll(): This method is used to retrieve all values from the preferences.
- getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences.
- getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences.
- getInt(String key, int defValue): This method is used to retrieve an int value from the preferences.
- getLong(String key, long defValue): This method is used to retrieve a long value from the preferences.
- getString(String key, String defValue): This method is used to retrieve a String value from the preferences.
- getStringSet(String key, Set defValues): This method is used to retrieve a set of String values from the preferences.
- registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to registers a callback to be invoked when a change happens to a preference.
- unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregisters a previous callback.
Following is sample byte code on how to write Data in Shared Preferences:
Источник
What is shared preference in Android-Kotlin?
Introduction
Shared-Preference is an interface to store and preserve data in android.
An interface is a class in the Object-Oriented-Programming concept, (OOP), which consists of methods or behavior of object belonging to that class. It accesses and modifies preference data returned by: Context.getSharedPreferences(String, int) .
A single instance of this class is called that all clients share.
An object of this class points to a file containing key-value pairs and provides simple methods to read and write them.
Handling shared preferences
The following methods can be called if you want to create a new shared preference file or share an existing file:
You can use this when you require more than one shared preference file, identified by name and specified with the first parameter. This can be called from any Context in your app.
This is used from an Activity if you need to use only one shared preference file for the activity. You don’t need to supply a name because this method retrieves a default shared preference file that belongs to the activity.
Note: Use a name that is uniquely identifiable to your app. Prefixing it with your app’s name is a good way to start.
Writing to shared preference
Call the edit() method on the instance of your SharedPreference you created. You can pass the keys and values that you want to write by using methods like putInt() and putString() . Then, to save changes, call apply() or commit() .
Reading from shared preference
You can read the data stored by calling methods like getInt() and getString() . You must provide the key for the desired value, and optionally include a default value to be returned in case the key is not present. For instance:
commit() and apply()
With commit() , your preferences change back from this Editor to the SharedPreferences object it is editing. This automically performs the requested modifications, replacing whatever is currently in the SharedPreferences . If two editors modify at the same time, the last one to call apply() wins.
Unlike commit() , which performs persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately in an asynchronous commit to disk and you won’t be notified of any failures.
If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
With apply() , you don’t need to worry about Android component lifecycles and their interaction. The framework ensures in-flight disk writes from apply() are completed before switching states.
Conclusion
Android has different life-cycle operations which range from onStart() , onCreate() , onPause() , onResume() , onStop() , onRestart() , onOrientationChange() , onStop() , onDestroyed() , etc. This means that when you use your android phone, these stages of lifecycle operation follow sequentially, get destroyed, and then are restarted again.
Data stored during the previous state get destroyed when another life-cycle started again.
Shared Preference is one of those four specific storage options to keep this data so that if a lifecycle gets destroyed, the app can access the previous data from the last operation, then rebuild. That is the reason for switching one app to the background (in simple terms) and retrieving it after a long time, upon which your app resumes from where it was pushed to the background.
Although Shared Preference stores primitive data in keys and values, its consistency is guaranteed.
Other options still exist such as shared storage (files, media, etc.), Database , and App-specific storage like the room database .
Источник