【发布时间】:2015-05-19 06:46:01
【问题描述】:
我有以下 RETROFIT API:
@POST("/payments")
Observable<Response> saveCreditCard(@Body CreditCard creditCard)
CreditCard 是 RealmObject。
当我尝试使用我的 API 方法时:
CreditCard card = realm.createObject(CreditCard.class);
card.setWhateverField(...);
...
mApi.saveCreditCard(card)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...);
我收到以下错误:
> retrofit.RetrofitError: com.fasterxml.jackson.databind.JsonMappingException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they where created.
System.err﹕ at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:400)
System.err﹕ at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
System.err﹕ at retrofit.RestAdapter$RestHandler$1.invoke(RestAdapter.java:265)
System.err﹕ at retrofit.RxSupport$2.run(RxSupport.java:55)
System.err﹕ at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
System.err﹕ at retrofit.Platform$Android$2$1.run(Platform.java:142)
System.err﹕ at java.lang.Thread.run(Thread.java:818)
System.err﹕ Caused by: java.lang.AssertionError: com.fasterxml.jackson.databind.JsonMappingException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they where created.
我假设 RETROFIT 在 io() 调度程序上对 JSON 进行序列化,因此出现错误。
有人对我如何克服 Realm 的线程问题有任何建议吗?
【问题讨论】:
-
似乎你必须有 Realm 的模型和 Retrofit 的第二个模型,并且有类来“转换”这些对象。
-
我们有 50 多个模型,所以这不是真正的解决方案。
-
我明白,但很有可能这是唯一的解决方案。
-
您可能需要手动将对象添加到您的领域。请查看文档 (realm.io/docs/java/latest/#other-libraries) 中的“改造”部分。
-
@geisshirt 请阅读问题的全文。注意“CreditCard card = realm.createObject(CreditCard.class);”。我正在发送一个领域数据库中的对象,而不是检索它,因此标题中包含“POST”。