I am making an app with users represented as RealmObject
and when the user logs in I have some code to check if the user already exists or if that user needs to be created based on an id.
public class User extends RealmObject {
@PrimaryKey
public String id;
public User(String id) {
this.id = id;
}
Code to check if a user exists:
public void checkUser(final HashMap<String, String> data) {
config = new SyncConfiguration.Builder(syncUser, Constants.realmUri)
.schemaVersion(0)
.build();
Realm.getInstanceAsync(config, new Realm.Callback() {
@Override
public void onSuccess(@NonNull Realm realm) {
AuthActivity.this.realm = realm;
// Check if user already exist
RealmQuery<User> query = realm.where(User.class);
query.equalTo("id", data.get("id"));
// Execute the query
User u = query.findFirst();
if (u == null) {
createUser(data);
Log.i("RealmHelper", "User did not exist");
} else {
if (u.isValid()) {
AuthActivity.this.userId = u.id;
startActivityMain();
Log.i("RealmHelper", "User did exist");
}
}
}
});
}
Constants.realmUri
equals a string with the ip and port of my server.
Now if the user exist the above code should obviously log that the user did exist. The problem is that I get the correct behaviour but if I create the user, enter the app, close the app and then remove the app data the checkUser()
method will return that the user did not exist when trying to log in the next time. I suspect that this has something do with local and remote realms and that the realm used in the checkUser()
method is somehow local rather than remote.
Despite checkUser()
saying that the user does not exist, the user is visible in Realm Studio and saved in the syncronized database as it has not been changed.
id
in User is coming from Facebook and the value remains the same which makes this problem even weirder.
I managed to solve this problem by using waitForInitialRemoteData() in the SyncConfiguration. This makes sure the realm is not empty after clearing app data.