Firebase database offline

Ruud van der Linden 6 Reputation points
2021-04-12T10:20:43.443+00:00

I'm using Firebase Database in my Xamarin Android app. It works fine, but I cannot get offline persistence to work. From what I'm reading I should just set SetPersistenceEnabled to true and KeepSynced to true on the database reference. Below my code for that part.

        public void Initialize()
        {
            FirebaseApp firebaseApp = FirebaseApp.InitializeApp(Application.Context);
            FirebaseDatabase.GetInstance(firebaseApp).SetPersistenceEnabled(true);
            firebaseDatabase = FirebaseDatabase.GetInstance(firebaseApp);
            firebaseAuth = FirebaseAuth.GetInstance(firebaseApp);
            firebaseStorage = FirebaseStorage.Instance;

            GetUser();
        }

        private async void OnLogin(LoginResultEventArgs e)
        {
            if (e.LoginResult == LoginResult.Succes)
            {
                projectsReference= firebaseDatabase.GetReference(firebaseAuth.CurrentUser.Uid + "/projects");
                projectsReference.KeepSynced(true);

            }
        }

Initialize is called from OnResume in my Splash activity.

When offline it doesn't work. For example below code. SetValueAsync never returns.

        public async Task AddProject(FRTDBProject project)
        {
            var reference = projectsReference.Push();
            var id = reference.Key;
            project.Id = id;
            await reference.SetValueAsync(FRTDBProject.FRTDBProjectModelToMap(project));
        }

Anyone has some working Xamarin Android offline Firebase database example or perhaps knows what the problem is?

Thanks.

Developer technologies .NET Xamarin
{count} votes

1 answer

Sort by: Most helpful
  1. Ruud van der Linden 6 Reputation points
    2021-04-21T07:42:32.34+00:00

    I've switched to AddValueEventListener() and SetValue() instead of SetValueAsync().

    Everything is working as expected now.

    Thanks for your help JarvanZhang.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.