Reading Data from Firebase


To read data at a path and listen for changes, use the addValueEventListener() method to add a ValueEventListener() to a DatabaseReference. This event will be triggered whenever there is a change in data in realtime. In onDataChange() you can perform the desired operations onto new data. Below is the event listener that is triggered whenever there is a change in user profile data:

 mDatabase.child( userId ).addValueEventListener(
   new ValueEventListener( ) {

     @Override
     public void onDataChange( DataSnapshot dataSnapshot ) {
       User user = dataSnapshot.getValue( User.class );
       Log.d( TAG, "User name: " + user.getName( ) + ", email " + user.getEmail( ) );
     }

     @Override
     public void onCancelled( DatabaseError error ) {
       // Failed to read value
       Log.w( TAG, "Failed to read value.", error.toException( ) );
     }
   }
 );

The listener receives a DataSnapshot that contains the data at the specified location in the database at the time of the event. Calling getValue() on a snapshot returns the Java object representation of the data. If no data exists at the location, calling getValue() returns null. The ValueEventListener also defines the onCancelled() method 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.

Offline Data
Firebase automatically stores the data offline when there is no internet connection. When the device connects to internet, all the data will be pushed to realtime database.