Unable to open a realm at path in Xamarin forms

I’m reading data from remote mongodb realm which sync’s to my local realm, but it seems I can’t read from my local realm after sync.

This is the message I get when I try to read from my local realm:

“Unable to open a realm at path ‘/data/user/0/com.companyname.appname/files/default.realm’: Incompatible histories. Expected a Realm with no or in-realm history, but found history type 3 Path:Exception backtrace:\n.”

here is my code:

private async Task OpenRealm()
{

    try
    {

        var user = App.realmApp.CurrentUser;

        //if user is not logged on yet log on the user and sync
        if (user == null)
        {


            var CurrentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
            var config = new SyncConfiguration("Hirschs", CurrentUser);
            _realm = await Realm.GetInstanceAsync(config);

            return _realm;

        }
        else
        {
            
            return _realm = Realm.GetInstance();

        }


    }
    catch (Exception ex)
    {
        await UserDialogs.Instance.AlertAsync(new AlertConfig
        {
            Title = "An error has occurred",
            Message = $"An error occurred while trying to open the Realm: {ex.Message}"
        });

        // Try again
        return await OpenRealm();
    }

}

The problem here is that you are trying to create a new local realm in the same path where the synced realm already is.

I suppose that you would like to open the same realm synchronously (that is necessary if the device is offline). In this case you would just need to use the same configuration for both the sync and async calls, as reported in the documentation here.

You could do something like:

private async Task<Realm> OpenRealm()
{
    try
    {
        var currentUser = App.realmApp.CurrentUser;

        if (currentUser == null)
        {
            var currentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
            var config = new SyncConfiguration("Hirschs", currentUser);
            _realm = await Realm.GetInstanceAsync(config);

            return _realm;
        }
        else
        {
            var config = new SyncConfiguration("Hirschs", currentUser);
            _realm = Realm.GetInstance(config);

            return _realm;
        }
    }
    catch (Exception ex)
    {
        await UserDialogs.Instance.AlertAsync(new AlertConfig
        {
            Title = "An error has occurred",
            Message = $"An error occurred while trying to open the Realm: {ex.Message}"
        });
    }
}
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.