-1

I have created a Room database and i am trying to implement the following functions

public int getRowCountSenderHelper()
    {
         return senderHelperDao.checkRowCount();
    }

    public SenderHelper getOneChat()
    {
        return senderHelperDao.getOneChat();
    }

Now the android is giving me this error.

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

Now i cannot use AsyncTask since they are deprecated and i cant call senderHelper.getOneChat() and senderHelperDao.checkRowCount() in a Thread because it need to return a value and i fear then when new thread goes to work in background the main thread may return empty value.

Any way to tackle this problem will be appreciated

M.Ahmed
  • 195
  • 1
  • 3
  • 13
  • Some useful workarounds can be found [here](https://stackoverflow.com/questions/58767733/android-asynctask-api-deprecating-in-android-11-what-are-the-alternatives). – momvart Mar 27 '21 at 16:56
  • Possible duplicate: https://stackoverflow.com/questions/44167111/android-room-simple-select-query-cannot-access-database-on-the-main-thread – Max Mar 27 '21 at 18:54
  • Does this answer your question? [Android Room - simple select query - Cannot access database on the main thread](https://stackoverflow.com/questions/44167111/android-room-simple-select-query-cannot-access-database-on-the-main-thread) – Max Mar 27 '21 at 18:56
  • @Max no the nature of question is different. The question you suggest ask about query not working while mine has some other problem. – M.Ahmed Mar 27 '21 at 20:07
  • @live-love asyncTask is deprecated. In the document it says its deprecated – M.Ahmed Mar 27 '21 at 20:08

1 Answers1

0

1- Define a variable of type LiveData and make a getter method for it.

2- make return that variable.

3-use getter to get the value of LiveData from your activity.

OathKeeper
  • 39
  • 1