Can't create handler inside thread that has not called Looper.prepare()- Spinner in Android-5

131 views Asked by At

Facing this issue in Android 5 while making dynamic UI, Although tried with xml too (working on 6-11). Any help will be appreciated.

     val spinner = Spinner(context) //ViewFactory.kt:186
     val spinnerAdapter = ArrayAdapter(context, R.layout.spinner_item, options)
     spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
     spinner.adapter = spinnerAdapter

Crash log

  java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    at android.os.Handler.<init>(Handler.java:200)
    at android.os.Handler.<init>(Handler.java:114)
    at android.widget.ListPopupWindow.<init>(ListPopupWindow.java:106)
    at android.widget.Spinner$DropdownPopup.<init>(Spinner.java:1063)
    at android.widget.Spinner.<init>(Spinner.java:205)
    at android.widget.Spinner.<init>(Spinner.java:144)
    at android.widget.Spinner.<init>(Spinner.java:129)
    at android.widget.Spinner.<init>(Spinner.java:102)
    at com.ro.ViewFactoryKt.buildSpinnerView(ViewFactory.kt:186)
    at com.ro.factory.ViewFactoryKt.buildSpinnerView$default(ViewFactory.kt:180)
    at com.ro.factory.LayoutFactoryKt.getSurveyDropdown(LayoutFactory.kt:153)
    at com.ro.Model.getSurveyLayout(SurveyModel.kt:793)
    at com.ro.api.SurveyAPI$getSurveyLayout$2.invokeSuspend(SurveyAPI.kt:159)
    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)
1

There are 1 answers

3
Alesh17 On

Most likely you are calling your code on the WorkerThread (not UI). Move your code to the MainThread and the error disappears.