Search code examples
androidrealm

Android: How to handle when Realm finishes sync?


I want to start (on background) sync with Realm Object Server when launching my Android app. And after data was successfully downloaded I want to show toast.

How I can do this? What method do I need to use? Thanks.


Solution

  • I have not tried this but it should work.

    private void setRealmDefaultConfiguration(SyncUser syncUser, String realmURL) {
        SyncConfiguration config = new SyncConfiguration.Builder(syncUser, realmURL)
                .waitForInitialRemoteData()
                .build();
        Realm.setDefaultConfiguration(config);
    }
    
    public abstract class BaseActivity extends Activity {
        private static boolean firstInit = true;
    
        protected Realm realm = null;
    
        @Override
        public void onCreate(Bundle bundle) {
            final boolean shouldShowToast;
            if(firstInit) {
                firstInit = false;
                shouldShowToast = true;
            } else {
                shouldShowToast = false;
            }
            super.onCreate(bundle);
            Realm.getInstanceAsync(Realm.getDefaultConfiguration(), new Realm.Callback() {
                @Override
                public void onSuccess(Realm realm) {
                    if(isChangingConfigurations() || isFinishing()) {
                        realm.close();
                    } else {
                        BaseActivity.this.realm = realm;
                        onRealmLoaded(realm);
                    }
                    if(shouldShowToast) {
                        Toast.makeText(BaseActivity.this, R.string.data.loaded, Toast.LENGTH_LONG).show();
                    }
                }
    
                @Override
                public void onError(Throwable throwable) {
                    // boop
                }
            });
        }
    
        protected void onRealmLoaded(Realm realm) {
            // override this if needed
        }
    }