-
Notifications
You must be signed in to change notification settings - Fork 16
B.5 Retrieve Data
This document covers the basics of retrieving data and how to order and filter Firebase data.
Firebase data is retrieved by attaching an asynchronous listener to a FirebaseDatabase reference. The listener is triggered once for the initial state of the data and again anytime the data changes.
Note: By default, read and write access to your database is restricted so only authenticated users can read or write data. To get started without setting up Authentication, you can configure your rules for public access. This does make your database open to anyone, even people not using your app, so be sure to restrict your database again when you set up authentication.
To read data from the database, you need an instance of DBReference by calling DB.getReference
var myRef:DBReference = DB.getReference();
You can listen for these types of events to retrieve data:
-
DBEvents.VALUE_CHANGED
Read and listen for changes to the entire contents of a path. -
DBEvents.VALUE_CHANGE_FAILED
If the client was not able to read values from server. -
DBEvents.CHILD_ADDED
Retrieve lists of items or listen for additions to a list of items. Suggested use with CHILD_CHANGE and CHILD_REMOVED to monitor changes to lists. -
DBEvents.CHILD_CHANGE
Listen for changes to the items in a list. Use with CHILD_ADDED and CHILD_REMOVED to monitor changes to lists. -
DBEvents.CHILD_REMOVED
Listen for items being removed from a list. Use with CHILD_ADDED and CHILD_CHANGE to monitor changes to lists. -
DBEvents.CHILD_MOVED
Listen for changes to the order of items in an ordered list.CHILD_MOVED
events always follow theCHILD_CHANGE
event that caused the item's order to change (based on your current order-by method).
You can use the VALUE_CHANGED
listener to read a static snapshot of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes. The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot returned is null.
Important: The VALUE_CHANGED
listener is called every time data is changed at the specified database reference, including changes to children. To limit the size of your snapshots, attach only at the highest level needed for watching changes. For example, attaching a listener to the root of your database is not recommended.
The following example demonstrates a social blogging application retrieving the details of a post from the database:
postReference.addEventListener(DBEvents.VALUE_CHANGED, onDataChange);
postReference.addEventListener(DBEvents.VALUE_CHANGE_FAILED, onCancelled);
function onDataChange(e:DBEvents):void
{
if (e.dataSnapshot.exists)
{
if (e.dataSnapshot.value is String) trace("String value = " + e.dataSnapshot.value);
else if (e.dataSnapshot.value is Number) trace("Number value = " + e.dataSnapshot.value);
else if (e.dataSnapshot.value is Boolean) trace("Boolean value = " + e.dataSnapshot.value);
else if (e.dataSnapshot.value is Array) trace("Array value = " + JSON.stringify(e.dataSnapshot.value));
else trace("Object value = " + JSON.stringify(e.dataSnapshot.value));
}
}
function onCancelled(e:DBEvents):void
{
trace("onCancelled: " + e.msg);
}
In onDataChange
you'll have access to a DBDataSnapshot that contains the data at the specified location in the database at the time of the event. Calling the value
property on a snapshot returns the AS3 object representation of the data. If no data exists at the location, calling value
returns null.
In this example, we are also listening for VALUE_CHANGE_FAILED
which that is called if the read is canceled. For example, a read can be canceled if the client doesn't have permission to read from a Firebase database location. This method is passed a DatabaseError object indicating why the failure occurred.
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. For example, a social blogging app might use these methods together to monitor activity in the comments of a post, as shown below:
ref.addEventListener(DBEvents.CHILD_ADDED, onChildAdded);
ref.addEventListener(DBEvents.CHILD_CHANGE, onChildChanged);
ref.addEventListener(DBEvents.CHILD_REMOVED, onChildRemoved);
ref.addEventListener(DBEvents.CHILD_MOVED, onChildMoved);
ref.addEventListener(DBEvents.CHILD_FAILED, onCancelled);
function onChildAdded(e:DBEvents):void
{
// A new comment has been added, add it to the displayed list
trace("onChildAdded, " + e.dataSnapshot.key);
}
function onChildChanged(e:DBEvents):void
{
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
trace("onChildChanged, " + e.dataSnapshot.key);
}
function onChildRemoved(e:DBEvents):void
{
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
trace("onChildRemoved, " + e.dataSnapshot.key);
}
function onChildMoved(e:DBEvents):void
{
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
trace("onChildMoved, " + e.dataSnapshot.key);
}
function onCancelled(e:DBEvents):void
{
trace("onCancelled: " + e.msg);
}
The onChildAdded()
callback is typically used to retrieve a list of items in a Firebase database. The onChildAdded()
callback is triggered once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data.
The onChildChanged()
callback is triggered any time a child node is modified. This includes any modifications to descendants of the child node. It is typically used in conjunction with the onChildAdded()
and onChildRemoved()
callbacks to respond to changes to a list of items. The snapshot passed to the event listener contains the updated data for the child.
The onChildRemoved()
callback is triggered when an immediate child is removed. It is typically used in conjunction with the onChildAdded()
and onChildChanged()
callbacks. The snapshot passed to the event callback contains the data for the removed child.
The onChildMoved()
callback 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
.
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.
Removing one of the CHILD_*
events will disable all the other ones also. So, make sure you are adding or removing these listeners always together.
Removing one of the SINGLE_VALUE_*
events will disable the other one also. So, make sure you are adding or removing these listeners always together.
In some cases you may want a callback to be called once, such as when initializing a UI element that you don't expect to change. You can use the SINGLE_VALUE_CHANGED
listener to simplify this scenario: it triggers once and then does not trigger again.
This is useful for data that only needs to be loaded once and isn't expected to change frequently or require active listening. For instance, the blogging app in the previous examples uses this method to load a user's profile when they begin authoring a new post:
var ref:DBReference = mDatabase.child("users").child(userId);
ref.addEventListener(DBEvents.SINGLE_VALUE_CHANGED, onDataChange);
ref.addEventListener(DBEvents.SINGLE_VALUE_CHANGE_FAILED, onCancelled);
You can use the DBQuery 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.
Note: Filtering and sorting can be expensive, especially when done on the client. If your app uses queries, define the .indexOn rule to index those keys on the server and improve query performance as described in Indexing Your Data.
To retrieve sorted data, start by specifying one of the order-by methods to determine how results are ordered:
- orderByChild() Order results by the value of a specified child key.
- 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:
// My top posts by number of stars
var myUserId:String = getUid();
var myTopPostsQuery:DBQuery = myRef.child("user-posts").child(myUserId).orderByChild("starCount");
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 the "starCount" child in each post. For more information on how other data types are ordered, see How query data is ordered.
To filter data, you can combine any of the limit or range methods with an order-by method when constructing a query.
- 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.
- endAt() Return items less than or equal to 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.
You can use the limitToFirst()
and limitToLast()
methods to set a maximum number of children to be synced for a given callback.
// Last 100 posts, these are automatically the 100 most recent due to sorting by push() keys
var myTopPostsQuery:DBQuery = myRef.child("posts").limitToFirst(100);
You can use startAt()
, endAt()
, 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.
This section explains how data is sorted by each of the order-by methods in the DBQuery
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 name in ascending order.
orderByKey
When using orderByKey()
to sort your data, data is returned in ascending order by key name.
- 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.
Enjoy building Air apps – With ♥ from MyFlashLabs Team
Introduction to Firebase ANEs collection for Adobe Air apps
Get Started with Firebase Core in AIR
- Prerequisites
- Add Firebase to your app
- Add the Firebase SDK
- Init Firebase Core
- Available ANEs
- Managing Firebase iid
Get Started with Authentication
- Add Authentication
- Init Authentication
- Manage Users
- Phone Number
- Custom Auth
- Anonymous Auth
- State in Email Actions
- Email Link Authentication
Get Started with FCM + OneSignal
- Add FCM ANE
- Init FCM ANE
- Send Your 1st Message
- Send Msg to Topics
- Understanding FCM Messages
- init OneSignal
- Add Firestore
- Init Firestore
- Add Data
- Transactions & Batches
- Delete Data
- Manage the Console
- Get Data
- Get Realtime Updates
- Simple and Compound
- Order and Limit Data
- Paginate Data
- Manage Indexes
- Secure Data
- Offline Data
- Where to Go From Here
Get Started with Realtime Database
- Add Realtime Database
- Init Realtime Database
- Structure Your Database
- Save Data
- Retrieve Data
- Enable Offline Capabilities
Get Started with Remote Config
- Add Storage ANE
- Init Storage ANE
- Upload Files to Storage
- Download Files to Air
- Use File Metadata
- Delete Files