Rock Lee Rock Lee - 1 year ago 88
Android Question

Realm `access from incorrect thread` error when using shared code between IntentService and AsyncTask (Android)

I have some code that downloads a "Current" object's JSON. But this same code needs to be called by an IntentService whenever an alarm goes off (when the app is not running any UI), and also by an AsyncTask while the app is running.

However, I got an error saying

Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
However, I do not understand how or why this stack trace got on a different thread.

I was able to get rid of the error by copying all the shared code and sticking it directly into DownloadDealService's
method, but it is very sloppy and I'm looking for a better solution that doesn't require duplicating code.

How can I get rid of this error, without duplicating code? Thanks.

public class DownloadDealService extends IntentService
protected void onHandleIntent(Intent intent)
Current todaysCurrent = Utils.downloadTodaysCurrent(); //<--- included for background info
String dateString = Utils.getMehHeadquartersDate(); //(omitted)
Utils.onDownloadCurrentCompleteWithAlarm(todaysCurrent, dateString); //<------ calling this...

public class Utils
// ...other methods ommitted...

//This method is not in the stack trace, but I included it for background information.
public static Current downloadTodaysCurrent()
//Set up Gson object... (omitted)
//Set up RestAdapter object... (omitted)
//Set up MehService class... (omitted)

//Download "Current" object from the internet.
Current current = mehService.current(MehService.API_KEY);
return current;

//Included for background info- this method is not in the stack trace.
public static void onDownloadCurrentComplete(Current result, String dateString)
if(result.getVideo() == null)
Log.e("HomePage", "Current was not added on TaskComplete");
remainder(result, dateString);

public static void onDownloadCurrentCompleteWithAlarm(Current result, String dateString)
//Set alarm if download failed and exit this function... (omitted)

remainder(result, dateString);//<------ calling this...

public static void remainder(Current result, String dateString)
Realm realm = RealmDatabase.getInstance();

//Add "Current" to Realm
Current current = Utils.addCurrentToRealm(result, realm); //<------ calling this...

public static Current addCurrentToRealm(Current current, Realm realm)
realm.beginTransaction(); //<---- Error is here
Current result = realm.copyToRealmOrUpdate(current);
return result;

Stack trace:

E/AndroidRuntime: FATAL EXCEPTION: IntentService[DownloadDealService]
Process: com.example.lexi.meh, PID: 13738
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
at io.realm.Realm.checkIfValid(
at io.realm.Realm.beginTransaction(
at com.example.lexi.meh.Utils.Utils.addCurrentToRealm(
at com.example.lexi.meh.Utils.Utils.remainder(
at com.example.lexi.meh.Utils.Utils.onDownloadCurrentCompleteWithAlarm(
at com.example.lexi.meh.Home.DownloadDealService.onHandleIntent(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(

I have an AsyncTask that calls some of those Utils methods also:

public class DownloadAsyncTask extends AsyncTask<Void, Integer, Current>
// ... (more methods ommitted)...

protected Current doInBackground(Void... voids)
return Utils.downloadTodaysCurrent(); //<---- shared Utils method

//Async class's callback in main activity:
public class HomePage extends AppCompatActivity implements DownloadAsyncTaskCallback, DownloadAsyncTaskGistCallback<Current, String>
// ... (more methods ommitted)...

public void onTaskComplete(Current result, String dateString)
Utils.onDownloadCurrentComplete(result, dateString);

Answer Source

[UPDATED] based on the additional info

RealmDatabase.getInstance() was returning the Realm instance created on the main thread. And this instance was used on the IntentService's thread. Which lead to the crash.

Realm instances can't be used on any other thread except the one on which they were created.

You can't pass Realm objects between the threads. What you can do is to pass a unique identifier of the object (i.e. @PrimaryKey), and then fetch the object by its' id on another thread. Like this: realm.where(YourRealmModel.class).equalTo("primaryKeyVariable", id).findFirst().

For more details check out Realm's official documentation and example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download