카테고리 없음

[Android java] How to solve "Cannot access database on the main thread ERROR"

happy_life 2022. 1. 12. 09:07

Cannot access database on the main thread  Error

 

*Thread 

(for someone who doesn't know what Thread is)

The unit of execution that operates within a process.
ex) When you access YouTube and watch videos in a process called Chrome Browser, you download YouTube data and watch them at the same time because you use several threads.

 

First, there are simple and complex methods.
A simple way is to attach allowMainThreadQueries() to the code that builds the DB.

 

But you shouldn't use this when you actually deploy an application.
When you connect to a database and import this and that, the application prioritizes DB-related tasks.
This is because the app can be Freeze. Therefore, it should operate on Background Thread, not  on Main Thread.

 

 

 

Using Runable and Thread, you should put all the code related to DB in the run() method in this way.

If you write the code in this way, you can handle the DB on the background thread.
I did the DB object creation outside the run method,(not  in  run()).Therefore, there was an error continuously.
I hope you don't be confused like me. lol :)