Skip to main content
← Blog
Desarrollo

Firebase for Xamarin.Forms — Part 3: FirebaseDatabase for Android

2 min read
Firebase for Xamarin.Forms — Part 3: FirebaseDatabase for Android

Continuing the Firebase Xamarin.Forms series — after implementing authentication for iOS and Android, we now tackle the Firebase Realtime Database on Android.

Adding the NuGet package

Search for and install Xamarin.Firebase.Database in your Android project.

Configuring the database URL

In MainActivity, add the database URL to the Firebase initialization:

private void InitFirebaseAuth() {
    var options = new FirebaseOptions.Builder()
        .SetApplicationId("1:2485447395:android:1bf7180db061f771")
        .SetApiKey("AIzaSyBdszK9ZCwbukS8Qb1iZ_LCXVq2os-KYJA")
        .SetDatabaseUrl("https://fir-sample-d9469.firebaseio.com")
        .Build();

    if (app == null)
        app = FirebaseApp.InitializeApp(this, options, "FirebaseSample");
}

The database URL is in the Firebase console under your project’s Realtime Database section.

Service interface (shared project)

using System;

namespace firebasesample.Services.FirebaseDB {
    public interface IFirebaseDBService {
        void Connect();
        void GetMessage();
        void SetMessage(String message);
        String GetMessageKey();
    }
}

Updating the UI

On the main screen (MainView), add a text entry and a save button:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             x:Class="firebasesample.Views.Main.MainView">
    <ContentPage.Content>
        <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
            <Label Text="Welcome! You are logged in."
                   VerticalOptions="Center" HorizontalOptions="Center" />
            <Entry HorizontalOptions="FillAndExpand"
                   Text="{Binding Message}" />
            <Button Text="Save"
                    Command="{Binding SaveTextCommand}"
                    BackgroundColor="#1FBED6"
                    HorizontalOptions="Fill"
                    TextColor="White" />
            <Button Text="Logout"
                    Command="{Binding LogoutCommand}"
                    BackgroundColor="#1FBED6"
                    HorizontalOptions="Fill"
                    TextColor="White" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

In the MainViewModel constructor:

private IFirebaseDBService _firebaseDatabaseService;

// In constructor:
_firebaseDatabaseService = DependencyService.Get<IFirebaseDBService>();
_firebaseDatabaseService.Connect();
_firebaseDatabaseService.GetMessage();
MessagingCenter.Subscribe<String, String>(
    this,
    _firebaseDatabaseService.GetMessageKey(),
    (sender, args) => { Message = args; }
);

Again we use messaging center here, as we did for Google Sign-In.

Android service implementation

public class FirebaseDBService : IFirebaseDBService {
    FirebaseDatabase database;

    public void Connect() {
        database = FirebaseDatabase.GetInstance(MainActivity.app);
    }

    public void GetMessage() {
        var userId = authService.GetUserId();
        databaseReference = database.GetReference("messages/" + userId);
        databaseReference.AddValueEventListener(new ValueEventListener());
    }

    public void SetMessage(string message) {
        var userId = authService.GetUserId();
        databaseReference = database.GetReference("messages/" + userId);
        databaseReference.SetValue(message);
    }
}

The ValueEventListener class handles real-time updates. It fires whenever the database value changes — whether from this device or another:

public class ValueEventListener : Java.Lang.Object, IValueEventListener {
    public void OnCancelled(DatabaseError error) { }

    public void OnDataChange(DataSnapshot snapshot) {
        String message = snapshot.Value.ToString();
        MessagingCenter.Send(FirebaseDBService.KEY_MESSAGE,
                             FirebaseDBService.KEY_MESSAGE,
                             message);
    }
}

The data structure we’ve used is simple — one message per user, stored at messages/{userId}. The same approach scales to more complex structures.

Testing real-time updates

To verify the real-time behavior: log in with the same account on two devices, change the message on one, and watch it update on the other. You can also edit the value directly in the Firebase console.

Full source code: https://github.com/jamontes79/xamarin-forms-firebase-sample

See you in Part 4 with the iOS database implementation.


More in Desarrollo