0

I have an android application that I do many realm operations. I wanted to do those stuff on background and to do that I have used handler threads.

I also used handler threads in some of my activities and service classes and I quit() those handler threads inside ofonTerminate() or onDestroy() methods.

However I do not know where should I quit the handler thread when I use it inside if a non-activity classes since they do not have onDestroy() methods. I have commented the handlerThread.quit() parts because one of them was giving an error. I have many class that has the similar implementation and I have implemented them in the same way. I was thinking closing handler threads after the work is done would make sense however something is wrong with it because I get the error when I uncomment the handlerThread.quit() lines.

    @Override
    public void find(Func1<RealmQuery<PlaylistSchedule>, RealmQuery<PlaylistSchedule>> query,
                     Action1<Result<List<PlaylistSchedule>>> onResult) {
        if (query != null) {
            handlerThread = new HandlerThread("MyHandlerThreadplaylistScheduleDao");

            handlerThread.start();
            looper = handlerThread.getLooper();

            Handler handler = new Handler(looper);

            handler.post(new Runnable(){
                @Override
                public void run() {
                    Timber.log(Log.DEBUG, "PlaylistDaoImpl", "find Thread.currentThread().getName() " + Thread.currentThread().getName());
                    mDatabase.findRealmObject(PlaylistSchedule.class, query,
                            result -> {

                                onResult.call(Result.getData(PlaylistScheduleMapper.copyFromRealm(result.data)));
                                //handlerThread.quit();
                            },

                            err -> {

                                onResult.call(Result.getError(err));
                                //handlerThread.quit();
                            }
                    );
                }
            });


        }

    }

The error that I have faced it is the following:

: Handler (android.os.Handler) {19be0f} sending message to a Handler on a dead thread

Thanks in advance.

Hilal
  • 902
  • 2
  • 22
  • 47
  • I am still here and waiting for advices ..Thanks – Hilal Dec 20 '19 at 15:21
  • 1
    Don't create a new handler thread for every query – EpicPandaForce Dec 28 '19 at 00:05
  • 1
    You are probably looking for https://github.com/Zhuinden/realm-monarchy – EpicPandaForce Dec 31 '19 at 06:35
  • @EpicPandaForce I have just seen your comment. Thank you so much for your reply. It will be difficult for me to change the implementation with the new library that you have shared. Is there a way to do the database operations with handler threads? Thank you – Hilal Jan 02 '20 at 19:48

0 Answers0