-1

How to correctly check if a record exists? In my case I get the error message.

In Fragment:
GroupDao groupDao = AppDatabase.getInstance(requireContext()).groupDao();

if (groupDao.isGroupExists(0)) {
 //
}

GroupDao:
@Query("SELECT EXISTS(SELECT * FROM group_table WHERE id = :groupId)")
    Boolean isGroupExists(Integer groupId);
Error:
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
andtompoi
  • 59
  • 7
  • 2
    What do you think the exception message means? – Scary Wombat Jul 11 '21 at 23:31
  • 1
    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) – Zain Jul 11 '21 at 23:41
  • You cannot run any database query or a network request on UI thread. Try reading the error message a bit more carefully next time, that is pretty self explanatory here – sinha-shaurya Jul 12 '21 at 05:24

2 Answers2

1

If you really want to make the query on the UI thread, add allowMainThreadQueries() on AppDatabase get.

fun get(context: Context): AppDatabase? {
        if (INSTANCE == null) {
            synchronized(AppDatabase::class) {
                INSTANCE = Room.databaseBuilder(context.applicationContext,
                        AppDatabase::class.java, "database.db")
                        .allowMainThreadQueries()
                        .build()
            }
        }
        return INSTANCE
    }
Paul Ng
  • 11
  • 1
0

Check error message.

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

fobidlim
  • 59
  • 5