在getItemCount()中获取kotlin.KotlinNullPointerException。 albumList返回null。也许我没有正确宣布albumList。我是Kotlin的新手。但我已成功地在Java中做过。
private var adapter: HomeAdapter? = null
private var albumList: ArrayList<Album>? = null
override fun onCreate(savedInstanceState: Bundle?)
{
albumList = ArrayList<Album>()
adapter = HomeAdapter(albumList)
recyclerView!!.adapter = adapter
}
class HomeAdapter(albumList: ArrayList<Album>?) : RecyclerView.Adapter<HomeAdapter.MyViewHolder>()
{
private var HomeContext: Context? = null
private var albumList: ArrayList<Album>? = null
fun HomeAdapter(albumList: ArrayList<Album>)
{
this.HomeContext = HomeContext
this.albumList = albumList
}
override fun getItemCount(): Int {
return albumList!!.size!!
}
}
class Album(s: String, i: Int)
{
private var name: String? = null
private var thumbnail: Int = 0
fun Album(name: String, thumbnail: Int)
{
this.name = name
this.thumbnail = thumbnail
}
}
问题是fun HomeAdapter()
不是构造函数,因此albumList
永远不会正确地赋值给非null值。
一般来说,代码看起来像是试图从Java翻译成Kotlin,并且是非常误导的,远非惯用的Kotlin。为了更好地了解它应该是什么样子,我建议你阅读官方文档(here)并使用IntelliJ Idea提供的自动Java到Kotlin转换。
为了给你一个想法,这是上面的Album
类的等效Java代码:
public final class Album {
private String name;
private int thumbnail;
public Album(String s, int i) {
super();
// Note you're not using "s" and "i" here
}
public final void Album(String name, int thumbnail) {
this.name = name;
this.thumbnail = thumbnail;
// note this is an instance method, not the constructor
}
}
我建议你再看看文档。但是要修复你的代码,这就是你的适配器应该看起来如何,你传递构造函数中的值,你不必担心空值,因为你没有传递任何空值
class HomeAdapter(val context: Context, val albumList: ArrayList<Album>): RecyclerView.Adapter<HomeAdapter.MyViewHolder>(){
override fun getItemCount(): Int {
return albumList.size
}
}
这是你的专辑Pojo如果你想能够分配变量然后你将它们声明为var因为你使用自动获得的数据toString,equals和hashCode
data class Album(val name: String, val thumbnailID: Int)