クラッシュの原因となる領域のスレッドがあります。なぜこれが許可されないのか、それを回避する方法がわかりません。ここで何が起こっているのいくつかのサンプルコードです:IntentServiceの領域 - スレッドがクラッシュしました
public class UploadPostService extends IntentService {
public UploadPostService() {
super("UploadPostService");
}
@Override
protected void onHandleIntent(Intent intent) {
String uniqueCode = intent.getStringExtra("uniqueCode");
OurApi api = OurApi.build(this, Application.apiRoot);
final Realm r = Realm.getDefaultInstance();
final RealmResults<Post> thePosts = r.where(Post.class)
.equalTo("post.code", uniqueCode)
.findAll();
if (thePosts != null && thePosts.size() > 0) {
for (final Post post : thePosts) {
api.uploadMedia(paramsToUpload, new Callback<Post>() {
@Override
public void success(Post postResponse, Response response) {
if (post.isValid()) {
r.beginTransaction();
post.setAField(blah); // CRASHES HERE
r.commitTransaction();
}
}
}
etc...
APIは、レトロフィットコールで終了した後、それは例外で、「ポスト」オブジェクト上の任意のフィールドの設定にクラッシュ:
"java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created."
私はこれに対する最もクリーンな解決策が何であるべきか不思議です。コールバックがIntentServiceとは異なるスレッド上にあると仮定します。私は実際のPostを更新する必要があります。別のレルムインスタンスを作成しようとしましたが、同じインスタンスから(明らかに)照会されていないので、ポストを更新することはできません。
これは私たちのコードにとって非常に重要なので、私はちょっと困惑しています。アドバイスを事前にありがとう!