- Начинаем работать с Firebase на Android
- Предпосылки
- 1. Использование Firebase Analytics
- Шаг 1: Настройка Firebase Analytics
- Шаг 2: Создание событий Analytics
- 2. Использование Firebase Auth
- Шаг 1: Настройте свой проект
- Шаг 2. Включение проверки подлинности на основе паролей
- Шаг 3: Поддержка регистрации пользователей
- Шаг 4: Поддержка входа пользователя
- Шаг 5: Поддержка выхода пользователя
- 3. Использование базы данных Firebase в реальном времени
- Шаг 1: Настройте свой проект
- Шаг 2: Запись данных
- Шаг 3: Чтение данных
- Заключение
- Work with Lists of Data on Android
- Get a DatabaseReference
- Kotlin+KTX
- Read and write lists
- Append to a list of data
- Listen for child events
- Kotlin+KTX
- Listen for value events
- Kotlin+KTX
- Detach listeners
- Sorting and filtering data
- Sort data
- Kotlin+KTX
- Kotlin+KTX
- Filtering data
- Kotlin+KTX
- Limit the number of results
- Kotlin+KTX
- Filter by key or value
- How query data is ordered
- orderByChild
- orderByKey
- orderByValue
- Next steps
Начинаем работать с Firebase на Android
Для мобильных приложений необходим сервер для выполнения таких задач, как проверка подлинности пользователей и синхронизация пользовательских данных на нескольких устройствах. Однако для создания такого сервера требуется набор навыков, которого не хватает большинству независимых разработчиков приложений. К счастью, есть несколько back-end как сервисных платформ, которые часто называют BaaS, которые вы можете использовать сегодня. Firebase от Google — одна из таких платформ.
Firebase бесплатно предоставляет такие важные услуги, как аналитика, отчеты о сбоях, аутентификация пользователей и облачные сообщения. Его услуги freemium включают в себя базу данных NoSQL в режиме реального времени, хостинг файлов и статический хостинг веб-сайтов.
В этом уроке я покажу вам, как добавить аутентификацию пользователей, аналитику и удаленное хранилище данных в приложение Android с помощью Firebase.
Предпосылки
Чтобы следовать материалу, вам понадобятся:
- Android Studio 2.2 RC2 или выше
1. Использование Firebase Analytics
Firebase Analytics является одним из самых популярных решений для аналитики мобильных приложений, доступных сегодня. Используя его, вы можете получить точное представление о том, кто ваши пользователи и как они используют ваше приложение.
Шаг 1: Настройка Firebase Analytics
В последних версиях Android Studio есть встроенная поддержка Firebase Analytics. Это означает, что вы можете добавить Firebase Analytics в свой проект, не покидая Android Studio.
Чтобы начать интеграцию Firebase Analytics с вашим проектом, нажмите «Сервис»> «Firebase». Вам будет предоставлено следующее окно помощника:
Нажмите «Аналитика», а затем «Зарегистрировать событие Analytics».
Теперь вы должны связать свой проект Android Studio с проектом Firebase. Поэтому нажмите кнопку «Подключиться к Firebase».
В появившемся диалоговом окне вы сможете увидеть все существующие проекты Firebase. Вы можете выбрать один из них или выбрать новый проект. На данный момент я предлагаю вам выбрать вариант «Создать новый проект Firebase» и дать уникальное имя проекту.
После нажатия кнопки «Подключиться к Firebase», которая находится внутри диалогового окна, Android Studio автоматически выполнит все необходимые изменения конфигурации, такие как создание файла google-services.json и загрузка SHA1.
Теперь вы можете нажать кнопку Добавить Google Analytics, чтобы добавить плагин Firebase и зависимость Firebase Core к вашему проекту. Android Studio покажет вам точные изменения, которые будут внесены в файлы build.gradle.
Нажмите «Принять изменения», чтобы завершить настройку.
Шаг 2: Создание событий Analytics
После того, как вы настроили Firebase Analytics для своего приложения, вам не нужно писать какой-либо дополнительный код, если вас устраивают только автоматически созданные события аналитики, такие как пользователь, открывающий ваше приложение в первый раз, использование приложения дольше чем 10 секунд, совершение покупки в приложении или удаление приложения. Таким образом, вы можете запустить приложение сейчас — на эмуляторе или на реальном устройстве — и в течение следующих 24 часов вы сможете увидеть журналы аналитики в консоли Firebase.
Если вы хотите более внимательно проанализировать поведение своих пользователей, вы можете создавать собственные события аналитики вручную, используя метод logEvent() класса FirebaseAnalytics . Метод ожидает два параметра: строку, определяющую имя настраиваемого события, и Bundle , содержащий сведения о событии в виде пар ключ-значение.
Например, если вы хотите генерировать событие с именем my_custom_event каждый раз, когда пользователь нажимает на определенную кнопку, вам нужно добавить следующий код в обработчик кликов кнопки:
По большей части пользовательские события неотличимы от автоматически собранных событий в консоли Firebase.
Обратите внимание, что имена событий чувствительны к регистру. Поэтому рекомендуется определять все имена событий как постоянные строки. Кроме того, вы можете использовать предопределенные константы имен событий, доступные в классе FirebaseAnalytics.Event .
2. Использование Firebase Auth
Пользовательская аутентификация является важным требованием для большинства приложений Android сегодня. Имея возможность надежно аутентифицировать своих пользователей и, таким образом, уникально идентифицировать их, вы можете предложить им индивидуальный опыт на основе их интересов и предпочтений. Вы также можете убедиться, что у них нет проблем с доступом к своим личным данным при использовании вашего приложения с нескольких устройств.
Firebase Auth позволяет вам аутентифицировать пользователей, используя различные механизмы входа. В этом уроке я покажу вам, как разрешить пользователям входить в ваше приложение, используя их адреса электронной почты и пароли.
Шаг 1: Настройте свой проект
Чтобы иметь возможность использовать Firebase Auth в вашем проекте Android Studio, вы должны добавить следующую compile зависимость к файлу build.gradle модуля app.
Шаг 2. Включение проверки подлинности на основе паролей
По умолчанию Firebase не разрешает аутентификацию пользователя. Таким образом, вы должны вручную включить аутентификацию пользователя на основе пароля в консоли Firebase. Для этого перейдите в раздел Auth и нажмите кнопку «Настройка входа в систему». Теперь вы увидите список всех доступных входных провайдеров.
Выберите «Электронная почта / Пароль», включите его и нажмите «Сохранить».
Шаг 3: Поддержка регистрации пользователей
При аутентификации на основе пароля новые пользователи должны регистрироваться, предоставляя уникальный адрес электронной почты и пароль. Чтобы добавить эту функциональность в свое приложение, вы можете использовать метод createUserWithEmailAndPassword() класса FirebaseAuth . Как следует из названия, метод ожидает, что в качестве аргументов будет указан адрес электронной почты и пароль.
Чтобы определить результат метода createUserWithEmailAndPassword() , вы должны добавить к нему OnCompleteListener , используя метод addOnCompleteListener() . В следующем фрагменте кода показано, как зарегистрировать нового пользователя, а также сообщить, успешно ли завершен процесс регистрации:
Обратите внимание, что вы несете ответственность за проверку адресов электронной почты и убедитесь, что пользователи используют надежные пароли.
Вы можете просмотреть адреса электронной почты всех успешно зарегистрированных пользователей на вкладке «Users» в разделе Auth в консоли Firebase.
Шаг 4: Поддержка входа пользователя
После успешной регистрации пользователь будет автоматически залогинен. Пользователь будет залогинен, даже если ваше приложение перезагрузится. Тем не менее, ваше приложение должно включать код, который позволяет пользователям выполнять вход в систему вручную, используя адрес электронной почты и пароль, которые они указали в процессе регистрации.
Чтобы залогинить пользователя вручную, вы должны использовать метод signInWithEmailAndPassword() класса FirebaseAuth . Метод ожидает адрес электронной почты и пароль в качестве его единственных аргументов и возвращает объект Task . Добавив к нему OnCompleteListener , вы можете проверить, был ли вход успешно завершен.
Чтобы избежать входа за пользователя, который уже вошел, вы должны вызвать метод signInWithEmailAndPassword() , только если текущий FirebaseUser имеет значение NULL .
В следующем фрагменте кода показано, как залогинить пользователя:
Шаг 5: Поддержка выхода пользователя
Чтобы отписать пользователя, вы можете просто вызвать метод signOut() класса FirebaseAuth .
3. Использование базы данных Firebase в реальном времени
Одна из самых мощных функций платформы Firebase — это база данных в режиме реального времени: все выполняемые на нем операции записи мгновенно доступны для всех клиентов, которые ее наблюдают. С помощью такой базы данных вы можете создавать приложения, которые позволяют пользователям беспрепятственно переключаться с одного устройства на другое, а также мгновенно взаимодействовать с другими пользователями.
Шаг 1: Настройте свой проект
Прежде чем использовать базу данных в режиме реального времени, вам придется добавить следующую compile зависимость к файлу build.gradle вашего модуля app:
Шаг 2: Запись данных
Вы можете представить базу данных в реальном времени как объект JSON. Это означает, что вы можете добавить к нему пары ключ-значение, где ключи всегда являются строками, а значения — это примитивы, массивы или другие объекты JSON.
Прежде чем писать в базу данных реального времени, вы должны получить ссылку на нее с помощью метода getInstance() класса FirebaseDatabase . Затем вы можете получить ссылку на любой путь внутри базы данных с помощью метода getReference() . Путь может содержать либо один ключ, либо несколько ключей, расположенных иерархически.
Когда у вас есть DatabaseReference к пути, вы можете установить его значение с помощью метода setValue() .
В следующем фрагменте кода показано, как добавить в базу данных простую пару «ключ-значение»:
Перейдя в раздел «Database» консоли Firebase, вы можете просмотреть все данные, находящиеся внутри базы данных в режиме реального времени.
Шаг 3: Чтение данных
Чтобы прочитать значение из базы данных в реальном времени, вы должны присоединить асинхронный наблюдатель к связанному ключу или пути. Точнее, вы должны присоединить объект ValueEventListener к объекту DatabaseReference , используя метод addValueEventListener() .
Метод onDataChange() ValueEventListener дает вам доступ к объекту DataSnapshot , метод getValue( ) может использоваться для получения последнего значения ключа.
Например, вот как вы можете получить значение, которое мы установили на предыдущем шаге:
Обратите внимание, что после добавления ValueEventListener метод onDataChange() запускается каждый раз, когда изменяется значение, которое оно отслеживает.
Заключение
Платформа Firebase устраняет необходимость в создании внутреннего сервера и позволяет сосредоточиться на создании лучших приложений. В этом уроке вы научились использовать его для добавления аналитики, аутентификации пользователей и облачного хранилища данных в реальном времени в свое приложение для Android.
Чтобы узнать больше о Firebase, вы можете обратиться к официальной документации. Вы также можете ознакомиться с нашим руководством по использованию Firebase Crash Reporting в Android:
Источник
Work with Lists of Data on Android
This document covers working with lists of data in Firebase. To learn the basics of reading and writing Firebase data see Read and Write Data on Android.
Get a DatabaseReference
To read and write data from the database, you need an instance of DatabaseReference :
Kotlin+KTX
Read and write lists
Append to a list of data
Use the push() method to append data to a list in multiuser applications. The push() method generates a unique key every time a new child is added to the specified Firebase reference. By using these auto-generated keys for each new element in the list, several clients can add children to the same location at the same time without write conflicts. The unique key generated by push() is based on a timestamp, so list items are automatically ordered chronologically.
You can use the reference to the new data returned by the push() method to get the value of the child’s auto-generated key or set data for the child. Calling getKey() on a push() reference returns the value of the auto-generated key.
You can use these auto-generated keys to simplify flattening your data structure. For more information, see the data fan-out example.
Listen for child events
When working with lists, your application should listen for child events rather than the value events used for single objects.
Child events are triggered in response to specific operations that happen to the children of a node from an operation such as a new child added through the push() method or a child being updated through the updateChildren() method. Each of these together can be useful for listening to changes to a specific node in a database.
In order to listen for child events on DatabaseReference , attach a ChildEventListener :
Listener Event callback Typical usage ChildEventListener onChildAdded() Retrieve lists of items or listen for additions to a list of items. This callback is triggered once for each existing child and then again every time a new child is added to the specified path. The DataSnapshot passed to the listener contains the the new child’s data. onChildChanged() Listen for changes to the items in a list. This event fired any time a child node is modified, including any modifications to descendants of the child node. The DataSnapshot passed to the event listener contains the updated data for the child. onChildRemoved() Listen for items being removed from a list. The DataSnapshot passed to the event callback contains the data for the removed child. onChildMoved() Listen for changes to the order of items in an ordered list. This event is triggered whenever the onChildChanged() callback is triggered by an update that causes reordering of the child. It is used with data that is ordered with orderByChild or orderByValue . For example, a social blogging app might use these methods together to monitor activity in the comments of a post, as shown below:
Kotlin+KTX
Listen for value events
While using a ChildEventListener is the recommended way to read lists of data, there are situations where attaching a ValueEventListener to a list reference is useful.
Attaching a ValueEventListener to a list of data will return the entire list of data as a single DataSnapshot , which you can then loop over to access individual children.
Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
Kotlin+KTX
This pattern can be useful when you want to fetch all children of a list in a single operation, rather than listening for additional onChildAdded events.
Detach listeners
Callbacks are removed by calling the removeEventListener() method on your Firebase database reference.
If a listener has been added multiple times to a data location, it is called multiple times for each event, and you must detach it the same number of times to remove it completely.
Calling removeEventListener() on a parent listener does not automatically remove listeners registered on its child nodes; removeEventListener() must also be called on any child listeners to remove the callback.
Sorting and filtering data
You can use the Realtime Database Query class to retrieve data sorted by key, by value, or by value of a child. You can also filter the sorted result to a specific number of results or a range of keys or values.
Sort data
To retrieve sorted data, start by specifying one of the order-by methods to determine how results are ordered:
Method Usage orderByChild() Order results by the value of a specified child key or nested child path. orderByKey() Order results by child keys. orderByValue() Order results by child values. You can only use one order-by method at a time. Calling an order-by method multiple times in the same query throws an error.
The following example demonstrates how you could retrieve a list of a user’s top posts sorted by their star count:
Kotlin+KTX
This defines a query that when combined with a child listener synchronizes the client with the user’s posts from the path in the database based on their user ID, ordered by the number of stars each post has received. This technique of using IDs as index keys is called data fan out, you can read more about it in Structure Your Database.
The call to the orderByChild() method specifies the child key to order the results by. In this case, posts are sorted by the value of their respective «starCount» child. Queries can also be ordered by nested children, in case you have data that looks like this:
In this example, we can order our list elements by values nested under the metrics key by specifying the relative path to the nested child in our orderByChild() call.
Kotlin+KTX
For more information on how other data types are ordered, see How query data is ordered.
Filtering data
To filter data, you can combine any of the limit or range methods with an order-by method when constructing a query.
Method Usage limitToFirst() Sets the maximum number of items to return from the beginning of the ordered list of results. limitToLast() Sets the maximum number of items to return from the end of the ordered list of results. startAt() Return items greater than or equal to the specified key or value depending on the order-by method chosen. startAfter() Return items greater than the specified key or value depending on the order-by method chosen. endAt() Return items less than or equal to the specified key or value depending on the order-by method chosen. endBefore() Return items less than the specified key or value depending on the order-by method chosen. equalTo() Return items equal to the specified key or value depending on the order-by method chosen. Unlike the order-by methods, you can combine multiple limit or range functions. For example, you can combine the startAt() and endAt() methods to limit the results to a specified range of values.
Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
Kotlin+KTX
Limit the number of results
You can use the limitToFirst() and limitToLast() methods to set a maximum number of children to be synced for a given callback. For example, if you use limitToFirst() to set a limit of 100, you initially only receive up to 100 onChildAdded() callbacks. If you have fewer than 100 items stored in your Firebase database, an onChildAdded() callback fires for each item.
As items change, you receive onChildAdded() callbacks for items that enter the query and onChildRemoved() callbacks for items that drop out of it so that the total number stays at 100.
The following example demonstrates how example blogging app defines a query to retrieve a list of the 100 most recent posts by all users:
Kotlin+KTX
This example only defines a query, to actually synchronize data it needs to have an attached listener.
Filter by key or value
You can use startAt() , startAfter() , endAt() , endBefore() , and equalTo() to choose arbitrary starting, ending, and equivalence points for queries. This can be useful for paginating data or finding items with children that have a specific value.
How query data is ordered
This section explains how data is sorted by each of the order-by methods in the Query class.
orderByChild
When using orderByChild() , data that contains the specified child key is ordered as follows:
- Children with a null value for the specified child key come first.
- Children with a value of false for the specified child key come next. If multiple children have a value of false , they are sorted lexicographically by key.
- Children with a value of true for the specified child key come next. If multiple children have a value of true , they are sorted lexicographically by key.
- Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.
- Strings come after numbers and are sorted lexicographically in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.
- Objects come last and are sorted lexicographically by key in ascending order.
orderByKey
When using orderByKey() to sort your data, data is returned in ascending order by key.
- Children with a key that can be parsed as a 32-bit integer come first, sorted in ascending order.
- Children with a string value as their key come next, sorted lexicographically in ascending order.
orderByValue
When using orderByValue() , children are ordered by their value. The ordering criteria are the same as in orderByChild() , except the value of the node is used instead of the value of a specified child key.
Next steps
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник