코딩스토리

[Android/ 안드로이드] Error : android.view.ViewRootImpl$CalledFromWrongThreadException 본문

Android/오류 해결

[Android/ 안드로이드] Error : android.view.ViewRootImpl$CalledFromWrongThreadException

라크라꾸 2020. 12. 17. 22:53

android.view.ViewRootImpl$CalledFromWrongThreadException: at android.view.ViewRootImpl.checkThread (ViewRootImpl.java:9816) at android.view.ViewRootImpl.requestLayout (ViewRootImpl.java:1845) at android.view.View.requestLayout (View.java:26338) at android.view.View.requestLayout (View.java:26338) at android.view.View.requestLayout (View.java:26338) at android.view.View.requestLayout (View.java:26338) at android.view.View.requestLayout (View.java:26338) at android.view.View.requestLayout (View.java:26338) at android.view.View.requestLayout (View.java:26338) at android.view.View.requestLayout (View.java:26338) at androidx.constraintlayout.widget.ConstraintLayout.requestLayout (ConstraintLayout.java:3172) at android.view.View.setFlags (View.java:16793) at android.view.View.setVisibility (View.java:11629) at com.lakue.lottoanalysis.activity.MainActivity$onResume$1$1.invokeSuspend (MainActivity.kt:217) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith (ContinuationImpl.kt:33) at kotlinx.coroutines.DispatchedTask.run (DispatchedTask.kt:56) at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely (CoroutineScheduler.kt:571) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask (CoroutineScheduler.kt:738) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker (CoroutineScheduler.kt:678) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run (CoroutineScheduler.kt:665)

 

앱을 실행했는데 다음과 같이 앱이 다운되는 현상이 발생할 경우가 있습니다.

 

 	CoroutineScope(Dispatchers.Main).launch {
                // Show progress from UI thread
                CoroutineScope(Dispatchers.Default).async {
                    // background thread
                    Gloval.winLottoData = db.userDao().getAll()
                    textView.visible = View.GONE

                }.await()
                // UI data update from UI thread
                // Hide Progress from UI thread
          }

 

오류의 원인은 TextView, ImageView와 같이 UI부분을 메인쓰레드에서 처리하게 되는데, 위의 코드에서는 textView.visible = View.GONE 코드는 UI관련 코드인데 background thread가 하는 곳에 있기 때문에 오류가 발생했습니다. 

 

이 문제를 해결하기 위해서는 UI부분에 해당하는  부분을 메인쓰레드에서 처리해 주면 해결됩니다.

 	CoroutineScope(Dispatchers.Main).launch {
                // Show progress from UI thread
                CoroutineScope(Dispatchers.Default).async {
                    // background thread
                    Gloval.winLottoData = db.userDao().getAll()

                }.await()
                // UI data update from UI thread
                // Hide Progress from UI thread
                textView.visible = View.GONE
          }
Comments