MainActivity.kt
class MainActivity : AppCompatActivity(), NewsItemclicked {
private lateinit var mAdapter: NewsListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
fetchData()
val adapter = NewsListAdapter( this)
recyclerView.adapter = mAdapter
}
private fun fetchData(){
val url = "https://saurav.tech/NewsAPI/top-headlines/category/sports/in.json"
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET,
url,
null,
Response.Listener {
val newsJsonArray = it.getJSONArray("articles")
val newsArray = ArrayList<News>()
for(i in 0 until newsJsonArray.length()){
val newsJsonObject = newsJsonArray.getJSONObject(i)
val news = News(
newsJsonObject.getString("title"),
newsJsonObject.getString("author"),
newsJsonObject.getString("url"),
newsJsonObject.getString("urlToImage")
)
newsArray.add(news)
}
mAdapter.updateNews(newsArray)
},
Response.ErrorListener{
}
)
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
}
override fun onItemClicked(item: News) {
}
}
在上面给出了一个新闻应用程序的MainActivity.kt。当我尝试运行该应用程序时,该应用程序正在崩溃。它显示lateinit属性mAdapter尚未初始化。请帮我解决这个问题。请尝试解释最简单的方法,因为我是Android的初学者,所以很难快速理解。
错误
E/AndroidRuntime:致命异常:main流程:com.example.newtoday,PID:10633java.lang.RuntimeException:无法启动活动ComponentInfo{com.example.newtoday.com/example.newsoday.MainActivity}:kotlin。UninitializedPropertyAccessException:lateinit属性mAdapter尚未初始化在android.app.ActivityThread.performLaunchActivity(ActivityThreads.java:2646)在android.app.ActivityThread.handleLaunchActivity(ActivityThreads.java:2707)在android.app.ActivityThread.-wrap12(ActivityThreads.java)网址:com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)网址:com.android.internal.os.ZygoteInit.main(ZygoteNit.java:756)由:kotlin引起。UninitializedPropertyAccessException:lateinit属性mAdapter尚未初始化
您似乎正在实例化适配器,并将引用存储在本地变量(adapter
)中,而不是专门创建的全局变量(mAdapter
)中,以便在收到网络请求的响应后更新其数据。
如果您将代码更改为:
mAdapter = NewsListAdapter(this)
崩溃就会得到解决。