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

One option is to update your query to this:

@Query("SELECT * FROM member_table WHERE MemberID=:id")
LiveData<Member> getMemberInfo(long id);

(or similar, using Flowable). This avoids the need to manually create your own AsyncTask.

Returning the LiveData wrapper around the Member type automatically signals to Room that the query can/should be performed asynchronously. Per https://developer.android.com/training/data-storage/room/accessing-data (my emphasis):

Note: Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time. Asynchronous queries—queries that return instances of LiveData or Flowable—are exempt from this rule because they asynchronously run the query on a background thread when needed.


You can use Future and Callable. So you would not be required to write a long asynctask and can perform your queries without adding allowMainThreadQueries() or using LiveData.

My dao query:-

@Query("SELECT * from user_data_table where SNO = 1")
UserData getDefaultData();

My repository method:-

public UserData getDefaultData() throws ExecutionException, InterruptedException {

    Callable<UserData> callable = new Callable<UserData>() {
        @Override
        public UserData call() throws Exception {
            return userDao.getDefaultData();
        }
    };

    Future<UserData> future = Executors.newSingleThreadExecutor().submit(callable);

    return future.get();
}

For me allowMainThreadQueries() works.

This allows room to support database access on the main thread.

See the following code

@Database(entities = [Word::class ],version = 1)
abstract class VocabularyDatabase:RoomDatabase() {

    companion object {
        private lateinit var INSTANCE:VocabularyDatabase
        fun getInstance(context:Context):VocabularyDatabase= Room.databaseBuilder(
            context,
            VocabularyDatabase::class.java,
             "vocabulary"

        )

            .createFromAsset("vocabulary.db")
            .allowMainThreadQueries()
            .build()

    }

    abstract fun dao():WordDao
}

Tags:

Android