Realm access from incorrect thread

后端 未结 4 2072
青春惊慌失措
青春惊慌失措 2020-12-06 09:35

I have an application with a LoginActivity, that when the user login correctly, I register to receive messages. And the LoginActivity jumps to

4条回答
  •  Happy的楠姐
    2020-12-06 10:35

    Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

    This error message is quite self-explanatory.

    As i see you're initializing realm by calling Realm.getDefaultInstance() on the UI thread.

    The error is coming from newMessageReceived(), so i guess that method is called from a background thread.

    Either obtain a Realm instance on the background thread and use that instead of the global instance:

    @Override
    public void run () {
        Realm backgroundRealm = Realm.getDefaultInstance();
        backgroundRealm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                Message receivedMessage = realm.createObject(Message.class, message.id);
                receivedMessage.setBodyMessage(message.message);
                receivedMessage.setFrom(message.from);
                receivedMessage.setTo(message.to);
                receivedMessage.setDelivered(false);
                receivedMessage.setMine(false);
                receivedMessage.setDate(Calendar.getInstance().getTime());
            }
        });
    }
    

    Or, if you would like to stick to the global Realm instance for some reason, then make sure your code is executed on the UI thread by calling runOnUiThread() (or directly posting a Runnable to the message queue of the main thread through a Handler):

    @Override
    public void newMessageReceived(final ChatMessage message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                realm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        Message receivedMessage = realm.createObject(Message.class,
                            message.id);
                        receivedMessage.setBodyMessage(message.message);
                        receivedMessage.setFrom(message.from);
                        receivedMessage.setTo(message.to);
                        receivedMessage.setDelivered(false);
                        receivedMessage.setMine(false);
                        receivedMessage.setDate(Calendar.getInstance().getTime());
                    }
                });
            }
        });
    }
    

提交回复
热议问题