Realm 3.5.0
在我的Application类中,我登录到Realm Object Server,成功后我设置了Realm set default configruation。
public class MyApp extends MultiDexApplication {
...
private void setRealmDefaultConfiguration(SyncUser syncUser, String realmURL) {
SyncConfiguration config = new SyncConfiguration.Builder(syncUser, realmURL)
.waitForInitialRemoteData()
.build();
Realm.setDefaultConfiguration(config);
}
}
行。
在我的片段中,我尝试获取Realm实例。
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
realm = Realm.getDefaultInstance(); // HERE THROW ERROR
return rootView;
}
}
但我得到错误:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: downloadAllServerChanges() cannot be called from the main thread.
at io.realm.SyncSession.checkIfNotOnMainThread(SyncSession.java:357)
at io.realm.SyncSession.downloadAllServerChanges(SyncSession.java:322)
at io.realm.internal.SyncObjectServerFacade.downloadRemoteChanges(SyncObjectServerFacade.java:176)
at io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:305)
at io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:284)
at io.realm.Realm.getDefaultInstance(Realm.java:281)
at com.myproject.fragment.MyFragment.onCreateView(OrganizationsFragment.java:147)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
.waitForInitialRemoteData()
使用网络,因此您不允许使用具有该设置的任何配置在UI线程上调用Realm.getInstance()
。这将是您的应用程序ANR。这也应记录在waitForInitialRemoteData
的Javadoc中。
相反,您可以使用Realm.getInstanceAsync()
,它会在后台线程上加载数据,并在Realm实例准备好后返回它。