所以我试图从API中获得数据,并将其改装为回收器视图适配器。一切都工作得很完美,比如将数据检索列表显示到列表项中。然而,当按下回收器视图的列表项并意图到另一个活动并意图返回到原始活动时,应用程序崩溃了。错误如下:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.marcusneo.stockportfolio, PID: 7586
java.lang.NullPointerException
at com.marcusneo.stockportfolio.MainActivity$getPortData$1.onResponse(MainActivity.kt:191)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1
导致错误的第191行是"response.body()!!let {detailAdapter.setData(it)}">
下面是从API检索数据的函数,它运行在onCreate()
private fun getDetailsData(keywords: String){
val retrofitData = retrofitBuilder.getCompDetails(keywords)
retrofitData.enqueue(object : Callback<IncomeState?> {
@SuppressLint("NotifyDataSetChanged")
override fun onResponse(call: Call<IncomeState?>, response: Response<IncomeState?>) {
if(response.isSuccessful){
if(response.body() != null){
response.body()!!.annualReports.let { detailAdapter.setData(it) }
binding.loadingDetail.visibility = View.GONE
binding.rvDetails.visibility = View.VISIBLE
} else {
binding.loadingDetail.visibility = View.VISIBLE
binding.rvDetails.visibility = View.GONE
}
} else {
Log.d("Response Errr", response.errorBody().toString())
}
}
override fun onFailure(call: Call<IncomeState?>, t: Throwable) {
Log.d("MainActivity","onFailure: " + t.message)
}
})
detailAdapter.notifyDataSetChanged()
}
我如何使response.body()!!不为零?
为了避免NullPointerException,定义一个变量,如val responseBody = responde.body()
,然后检查该变量是否为空:
if (response.isSuccessful) {
val responseBody = response.body()
if (responseBody != null) {
responseBody.annualReports.let { detailAdapter.setData(it) }
binding.loadingDetail.visibility = View.GONE
binding.rvDetails.visibility = View.VISIBLE
} else {
binding.loadingDetail.visibility = View.VISIBLE
binding.rvDetails.visibility = View.GONE
}
} else {
Log.d("Response Errr", response.errorBody().toString())
}