@maximsemin23

Ошибка при попытке создания object: Runnable?

AndroidViewModel
class AppViewModel (application: Application) : AndroidViewModel(application) {
    var currentTemperature : MutableLiveData<Int> = MutableLiveData()
    lateinit var temperatureHandler: Handler
    private val applicationContext: Context by lazy { getApplication() }

    private val updateTemperature = object : Runnable {
        override fun run() {
            while (true) {
                temperatureHandler.postDelayed(this, 1000)
                currentTemperature.value = getBatteryTemperature(applicationContext)
            }
        }
    }

    init {
        updateTemperature.run()
    }
}

Ошибка
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maximsiomin.batterytemperature/com.maximsiomin.batterytemperature.ui.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.maximsiomin.batterytemperature.viewmodel.AppViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.maximsiomin.batterytemperature.viewmodel.AppViewModel
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:238)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
        at com.maximsiomin.batterytemperature.ui.MainActivity$temperature$2.invoke(MainActivity.kt:12)
        at com.maximsiomin.batterytemperature.ui.MainActivity$temperature$2.invoke(MainActivity.kt:11)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at com.maximsiomin.batterytemperature.ui.MainActivity.getTemperature(Unknown Source:2)
        at com.maximsiomin.batterytemperature.ui.MainActivity.onCreate(MainActivity.kt:20)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130) 
        at com.maximsiomin.batterytemperature.ui.MainActivity$temperature$2.invoke(MainActivity.kt:12) 
        at com.maximsiomin.batterytemperature.ui.MainActivity$temperature$2.invoke(MainActivity.kt:11) 
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74) 
        at com.maximsiomin.batterytemperature.ui.MainActivity.getTemperature(Unknown Source:2) 
        at com.maximsiomin.batterytemperature.ui.MainActivity.onCreate(MainActivity.kt:20) 
        at android.app.Activity.performCreate(Activity.java:7802) 
        at android.app.Activity.performCreate(Activity.java:7791) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
     Caused by: kotlin.UninitializedPropertyAccessException: lateinit property temperatureHandler has not been initialized
        at com.maximsiomin.batterytemperature.viewmodel.AppViewModel.getTemperatureHandler(AppViewModel.kt:12)
        at com.maximsiomin.batterytemperature.viewmodel.AppViewModel$updateTemperature$1.run(AppViewModel.kt:18)
        at com.maximsiomin.batterytemperature.viewmodel.AppViewModel.<init>(AppViewModel.kt:25)
        at java.lang.reflect.Constructor.newInstance0(Native Method) 
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343) 
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130) 
        at com.maximsiomin.batterytemperature.ui.MainActivity$temperature$2.invoke(MainActivity.kt:12) 
        at com.maximsiomin.batterytemperature.ui.MainActivity$temperature$2.invoke(MainActivity.kt:11) 
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74) 
        at com.maximsiomin.batterytemperature.ui.MainActivity.getTemperature(Unknown Source:2) 
        at com.maximsiomin.batterytemperature.ui.MainActivity.onCreate(MainActivity.kt:20) 
        at android.app.Activity.performCreate(Activity.java:7802) 
        at android.app.Activity.performCreate(Activity.java:7791) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 

Если закомментировать
init {
        //updateTemperature.run()
 }

То будет работать. То есть при попытке вызова runnable объекта возникает ошибка. На стаковерфлоу вообще не нашёл такой темы, как исправить
Вот код MainActivity на всякий случай
class MainActivity : AppCompatActivity() {
    private val temperature by lazy { ViewModelProviders.of(this).get(AppViewModel::class.java)}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val temperatureTextView: TextView = findViewById(R.id.temperature_number)
        val temperatureObserver = Observer<Int> { currentTemperature -> temperatureTextView.text = currentTemperature.toString() }
        temperature.currentTemperature.observe(this, temperatureObserver)
    }
}


Что можно сделать?
  • Вопрос задан
  • 66 просмотров
Решения вопроса 1
zagayevskiy
@zagayevskiy Куратор тега Android
Android developer at Yandex
Нет, неправда, ошибка при создании вьюмодели, потому что UninitializedPropertyAccessException: lateinit property temperatureHandler has not been initialized.
Ты пообещал (lateinit) компилятору, что инициализируешь temperatureHandler позже, и не сделал этого. При обращении к этой проперти рантайм тебя наказал падением. Инициализируй её.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы