简体   繁体   中英

Realm Xamarin.Forms can't find existing item

I am working to implement Realm Platform with synced realms on a Xamarin.Forms Android and iOS app. Using the code below I can create/connect to the realm instance which should store the data and I can add new objects to the instance. However, no matter what I do I cannot get

realm.Find<Person>("ID-1");

to return anything. In a try() catch() that line returns: "Object reference not set to instance of an object". Using Realm Studio I can see the changes being made, and I see that the object which I'm looking for on the app exists.

Furthermore, if I try to query for elements I always get 0, no matter which parameter I specify.

Model:

public class Person : RealmObject
{
    [PrimaryKey]
    public string Id { get; set; }

    public int Number {get; set;}

    public string DeviceName { get; set; }
    public string DeviceId { get; set; }

    public IList<SoundSnapModel> SnapList { get;}

    public Person()
    {

    }
}

Code snippet:

 var credentials = Credentials.Nickname("Thanos", false);
 var InstanceId = "instance-name";
 var serverURL = new Uri("realms://" + InstanceId + "/~/testRealm3");
 var AUTH_URL = new Uri("https://" + InstanceId + "/auth");
 var user = await User.LoginAsync(credentials, AUTH_URL);

 var configuration = new QueryBasedSyncConfiguration(serverURL, user);
 var realm = Realm.GetInstance(configuration);

 realm.Write(() => realm.Add(new Person { Id = "ID-1", Number = 123,     
 DeviceId = "something", DeviceName = "something" }));  // works without issue
 Debug.WriteLine("Added new person!!");

 var elements = realm.All<Person>().Where(e => e.Number > 100);
 Debug.WriteLine("Found the object list: " + elements.Count() + "  "); // returns 0

 var currentObject = realm.Find<Person>("ID-1"); // triggers the exception mentioned above

The QueryBasedSyncConfiguration was added after I left the Realm Xamarin team but I think it's not working because you're not configuring it fully.

Looking at the docs it is fairly clear you must setup the subscription .

By default, a query-based synchronized Realm contains no data. Instead, the client application must choose, or subscribe to, which subset of data in the corresponding Realm on the server it wants to synchronize.

You don't create a subscription as they describe:

var subscription = realm.All<Person>().Where(e => e.Number > 100).Subscribe();

I'm fairly sure that, even though you are creating data locally, it's effectively not existing locally until you have a subscription which would include it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM