我刚开始使用这个新应用程序,想看看我是否通过Retrofit得到任何响应并将其打印在TextView中。
但是应用程序在没有任何堆栈跟踪的情况下崩溃,因此没有异常......只是没有。
我有一个Retrofit界面和一个“工厂”,它创建了请求,所有东西都通过Kotlin Coroutine在不同的线程中运行。
class MainActivity : AppCompatActivity() {
private lateinit var debugTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
debugTextView = findViewById(R.id.debugTextView)
val service = RetrofitFactory.makeCarDataService()
GlobalScope.launch(Dispatchers.Main) {
val request = service.getData()
val response = request.await()
debugTextView.text =response.toString()
}
}
}
我想发布一个错误...但没有,一切都应该完美运行:/
要使用Dispatchers.Main
,我们需要将以下行添加到应用程序的build.gradle文件依赖项中:
实现'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
缺少这种依赖性可能是应用程序崩溃而没有任何堆栈跟踪的原因。
没有堆栈跟踪,这些是可能的问题:
service.getData()
可以扔NullPointerException
debugTextView.text
可以扔NullPointerException
response.toString()
可以扔NullPointerException
我对协同程序不是很熟悉,但是你是否只在设置视图上的文本时尝试使用主线程?这样的事情:
val service = RetrofitFactory.makeCarDataService()
GlobalScope.launch(Dispatchers.Default/*change here*/) {
val request = service.getData()
val response = request.await()
/*change here*/
withContext(Dispatchers.Main) {
debugTextView.text = response.toString()
}
}
}
try {
val request = service.getData()
val response = request.await()
debugTextView.text =response.toString()
} catch (e: RuntimeException) {
e.printStackTrace()
} catch (t: Throwable) {
t.printStackTrace()
}